text:
Control a motor with a button
Code:
int motorPin = 9;  // the pin the motor is connected to

void setup()
{
 pinMode(motorPin, OUTPUT);
}

void loop()
{
 motorOnThenOff(); //motorAcceleration
}

void motorOnThenOff(){
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  digitalWrite(motorPin, HIGH); // turns the motor On
  delay(onTime);                // waits for onTime milliseconds
  digitalWrite(motorPin, LOW);  // turns the motor Off
  delay(offTime);               // waits for offTime milliseconds
}

void motorOnThenOffWithSpeed(){

  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
  int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
  delay(offTime);                   // waits for offTime milliseconds
}

void motorAcceleration(){
  int delayTime = 50; //milliseconds between each speed step

  //Accelerates the motor
  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }

  //Decelerates the motor
  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
    analogWrite(motorPin, i);   //sets the new speed
    delay(delayTime);           // waits for delayTime milliseconds
  }
}

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.
This is the circuit:
https://circuits.io/circuits/4267039-spin-motor-spin/edit
How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

add this variable at the top of your program:
const int buttonPin = XX;   // the pin for the button
bool bState = false;

in the setup() function:
pinMode(buttonPin, INPUT_PULLUP);
// in case INPUT_PULLUP is not defined, comment the above line and uncomment below
//pinMode(buttonPin, INPUT);
//digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:
update_bState();

if (bState) { digitalWrite(motorPin, HIGH); }
else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:
void update_bState(void)
{
    static bool buttonDone = false;
    static uint16_t timeButton;

    if (!digitalRead(buttonPin))
    {
        if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
        { // Do once when button is pressed for at least 100ms (debounce)
            bState ^= true;     // Toggle button state
            buttonDone = true;
        }
    }
    else
    {
        buttonDone = false;
        timeButton = millis();
    }
}

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D
By the way, I did not tested any code, so there may be some typo errors...

Yes I do, first line I tell to add in the loop

I beg your pardon, so you do

No problem. I checked, I could have forgotten something.

you have some issues in the circuit too, you need to put pull up or pull down resistors with push button in order to stop floating values.

@Muhammad Did you notice that the button is initialized as INPUT_PULLUP? This enables internal microcontroller pull-up resistor for the pin, thus avoiding the use of external pull for the button.

I also used that KEYWORD twice but it didn't work for me that's why I ask about that.

@Muhammad depending your board definitions or arduino version, INPUT_PULLUP may not be defined. In this case, pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); should work. Writing a 1 to an input declared pin turns the internal pull-up on.

Thanks for sharing such information and for enhancing my knowledge.


text:
Custom function like yield
As far as I understand, yield() is used when you have long code (e.g. loop) so the background processing required by the esp8266 is not suspended for long time.
I have application where some sound should be running all the time and in the same time the program has to do other things which may includes long loops (that I call yield() inside them). Those long loops cause the sound to be discontinues.
What is the best idiomatic way of imitating the yield() function in my program so I do some thing like this:
for(int i=0;i<10000;++i){
    yield();
    customeYield();
    someFunction(i);
}

Where customeYield() contains the necessary instruction for playing the sound. It is exactly like this (I am using ESP8266Audio):
if (mp3_->isRunning()) {
    if (!mp3_->loop()) {
        mp3_->stop();
        return true;
    }
    return false;
}
return true;

Of course, I can just call it like I did (making it global or something). However, I was wondering if there is a standard way for such a task.

yield() must be called in some time interval or watchdog restarts the esp8266. you must call your function or the music stops. no magic. yield() does what is needed and returns.

Without any hint, what you are actually doing in your long loops, it is difficult to say, what way would be the best for your case. I don't believe, there is a standard way of doing this, but there are basically only two ways of multitasking on a microcontroller:

Interrupt driven: You can set a timer interrupt, that occurs regularly to call the AudioGenerator::loop() function (which fills the buffer with the next data).
Non-blocking code: If you are using non-blocking code, you can first do one thing and then do another in sequence, so fast, that both codes are executed often enough. Thats exactly what the library you use is designed for (according to the README file).

If you are using more than one of these long loops in your loop() function, you may consider doing things with a finite state machine (FSM), so that you don't have to always add the AudioGenerator::loop() function to your long loops, but only once for the normal loop() function.

Thank you very much for your reply. Actually, yes I am using FSM. However, I did not understand exactly how this will change things? At the end, if some state main function contains long loop it will still suspend the other code from being executed.. Did I miss sth ?

The FSM can help you to divide your long loops into small parts, so that one execution of the main loop() function does not take long. Then you execute the AudioGenerator::loop() in every cycle of the main loop() function. With this you suspend the long loop a bit for executing the background task (here: playing audio) in between. That is just a coding style. How exactly to divide the long loops into small parts depends on the code inside of them. I hope this is now clearer.

AH Ok! I got it now.. I thought there is native support for the pattern. I am implementing it the way you advice and It seems working.. Thank you very much!

source: Stack Exchange

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

sort: votes


text:
ESP8266 with Arduino Uno and HTTP POST
Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.
My problem with it is how can I program the esp with arduino uno? Do I do something like this

https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??
Thanks for helping

That would work if your ESP8266 had the AT+ firmware flashed onto it by default. What exact module do you have? If you have a NodeMCU board you might as well work on the ESP8266 directly for everything

Im using the small one with 8 pins (esp-01). Thanks

Yes, the library

https://github.com/bportaluri/WiFiEsp

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.
If that is not the case you can download the binary image here and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.
For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.

Is it ok if i use something like this to connect so can use 5V instead? link

@HenrikhA. The ESP8266 is a 3.3V device, if you supply it with 5V it dies. It should also not receive a 5V signal. You will need a level shifter from the Arduino TX line to the ESP's RX line with a voltage divider. See http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/

@HenrikhA. Ah, I didn't see the link at the end. Yes, the adapter has a voltage regulator and bi-directional level shifters already on there. This module should be fine and you could give +5V (or V_USB) as VCC on there.

I think I know what to do now. Thanks @Maximilian

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


text:
how to know the channel i receive information from when i use nRF24L01 to connect between 3 of them
i am using nRF24L01 to connect between 3 of them ( 1 is master and the others are slaves) and i am using nRF24 library , my problem is that when the master receive something from the other slaves and do not know from which channel the infromation come so is there is a way to know from which channel
//master channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[1]); // mastr
  radio.openReadingPipe(2, addresses[0]); // carwl
  radio.openReadingPipe(2, addresses[2]); // carwl2
//slave 1 channel code :
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // carw1
  radio.openReadingPipe(2, addresses[1]); // mastr
//slave 2 channel code:
  const byte addresses[][6] = {"00001", "00002","00003"};
  radio.openWritingPipe(addresses[0]); // 00003
  radio.openReadingPipe(2, addresses[2]); // 00002
library i use: https://github.com/nRF24/RF24

You can pass theRF24.available function a pointer to a variable. The available function will write the pipe-number of the message to that variable.
An example can be found in the documentation

The nRF24 is highly versatile and can be programmed for a number of different network topologies.  It appears you want either

One-to-many network - where the master node sends data to the slave nodes
Many-to-one network - where the master receives data from many slaves.

Both networks are achieved with the same radio channel (RF_CH) on all nodes.
For a one-to-many network you need to have a different RX address for each slave node.  Set the master TX address to the RX address of the corresponding slave  that you want to receive the data.  Done.
For a many-to-one network you are limited to 6 slave nodes.  On the master radio you will need to set the addresses of data pipes 0-5 to the slave TX addresses.  The master will be listening for data on all pipes and signal an interrupt whenever data is received on any of them.
To achieve bi-directional communication with a (practically) unlimited number of slave nodes, your best bet is to use the in-built ACK PAYLOAD feature of nRF24.  In addition to configuring a one-to-many network, you need to enable ACK payload on each radio node.  The procedure to follow is given in the nRF24L01 data sheet.  I can't recommend strongly enough how important that is to read and learn from.  You will be able to send a message from the master to one slave, and get data back from that node in the same radio transmission, auto-retransmit etc included in the bargain.  This way you also know which node the data are coming from - without needed to encode the identity of the slave node in the message.  It's incredible what these little radios will let you achieve!


text:
Can an Arduino be used to read data from a serial port?
People often use Arduinos to send data over serial to other peripherals (flashing firmware onto modules, etc) by pulling RES to ground,  connecting the TX and RX pins to the device being programmed, and then sending data to the Arduino over serial. As an alternative, one could also remove the ATmega instead of grounding RES.
That being said, there should be no reason why one could not receive data from a connected device in the same way. However, no matter what I try, I never succeed in using an Arduino to relay serial input from another device over USB.
I have even tried setting up a simple echo to no avail (even though the TX and RX LEDs flash):
Is it even possible?

When you program a device in the way you suggest data is already flowing in both directions. That is why you have to connect both TX and RX to the other device. There must be something fundamentally wrong with your setup for your loopback test to fail.

@Majenko I am using Arduino's own serial monitor and have an Arduino Nano/Uno (tried both) connected to my computer, with the RESET pin being pulled to ground, and TX connected to RX. Sound alright?

@Majenko I have also tried this with another laptop, and different serial monitors (picocom, minicom and screen)

Well, I just replicated the circuit you show above and used minicom and it worked perfectly.

Mine is a genuine Arduino Uno. Is yours?

@Majenko Yep. Strangely, when I connect another Arduino that is outputting something to serial, I can get this to work.. But the loopback still doesn't work...

Yes, it can, and the wiring diagram you have drawn works perfectly for me using minicom in Ubuntu.
The majority of serial communication is bi-directional anyway - especially when using it to program a device.
There is absolutely no difference between interfacing the built-in USB->UART adaptor to an external device of your choice and interfacing it with the ATMega328P chip. Just because the ATMega328P chip is on the same board doesn't make it in any way special - it is just a UART interfaced device.
If your setup is not working you can try:

Physically remove the ATMega328P chip to see if that is interfering even when held in reset
Check for software that may be interfering with your communication, such as the notorious ModemManager.

I have tried removing the ATMega from the Uno, and also tried using a Windows laptop. That being said, however, you have answered my question, so I will accept this as an answer. Troubleshooting my issue seems off topic for this site.

Maybe your wires are not working right.

Hmm, the wires work fine when the serial in is coming from another Arduino (running a sketch)

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


text:
Uploading to atmega328 over serial with arduino bootloader running at 2MHz
I want to run an atmega328 on a breadboard at 2MHz and upload to it via the serial pins (pins 2 and 3). So I am setting the clock divide by 8 fuse bit to enable this, meaning the atmega runs at 2MHz eith the 16MHz crystal. But I can't upload, probably because the bootloader is not expecting the clock to be running at 2MHz. The baud rates are probably mismatched by 8 times, the IDE is trying to upload at 57600 but since the bootloader code is not aware its being clocked at 2MHz, its probably running 8 times too slow. I've messed around a bit with the arduino conf files changing baud rates but had no joy. I was wondering if anyone knows how to do this off the top of their head.
Thanks, Pete

Edit the programmers.txt file somewhere inside the arduino folder. Duplicate the avrisp section. Replace avrisp. with avrispslow. or something, and change the .name=AVR ISP with .name=AVR ISP Slow. Add avrispslow.speed=7200 and avrispslow.program.speed=7200. Restart the IDE. You should now have a new item in the Boards=>Programmers menu.

Thanks, thats basically what I was looking for but in the end it didn't work. I believe the reason is that my PC do that baud rate without certain extra measures which are not practical (ie using new style termios2 struct for serial access). So I ended up using Ignacios method.

Unprogram the CKDIV8 fuse and add the following to the sketch instead, near the beginning:
#include <avr/power.h>

void setprescaler(void) __attribute__ ((naked)) \
  __attribute__ ((section(".init1")));

void setprescaler(void)
{
  clock_prescale_set(clock_div_8);
}

This will do essentially the same thing as the fuse, but won't interfere with the bootloader.

Is there not a risk to running the atmega out of its SOA even if only for a few cycles? I guess I could use that technique while working on the project and change to fuse divider for 'production' but I was wondering if theres either a setting in the IDE to modify the serial speed during upload, or a easy way to set the baud in the bootloader, even if it means recompiling it.

What voltage are you running it at, 1.8V?

If you are running at 1.8V, I don't see how you can be using a serial upload, because the voltages will be too high. If you are running at 5V you can do what Ignacio Vazquez-Abrams suggested.

No I'm initially trying at 5v just to get it working before dropping to 3.6, the project has a SD card (currently unplugged) which determines the voltage. So I also have to work on it at 3.6 to avoid damage to the SD. I use the usbasp and today, I bricked 2 atmega328s. I only have one left until my next order turns up. What's happening is if I forget to switch the usbasp back to 5v before uploading, the fuses get set to 0, setting the reset pin to disable, bricking the chip. PITA.

Don't know why this happens but it does (I get an error at the end of upload about fuse settings not matching, despite code upload apparently succeeding). Since I need 3.3v for SD I have to clock lower than 12MHz but only have 16MHz crystals hence divider bit. Plan is to use serial instead of USBASP to avoid fuse bits being touched during upload. All works fine if I disable clock divider, so problem is related to speed.

The maximum characterized speed for 3.3V is 13.3MHz, but many people report success at 16MHz with AVR devices, myself included (I have a ATmega1284P connected to a 3.3V display and a 16MHz crystal, no prescaler). Although I did make myself a passive level shifter so that I can keep my programmer at 5V.

Thanks, I ended up doing this for reasons explained above. Ill set the fuse and remove the divider code when the code is done.

There's no need to remove the prescale code; once the fuse is set it will become a no-op.

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


text:
Measurement of pulse duration greater than 3mins
Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately.
I've tried using interrupts but haven't come up with a correct solution yet.
I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around 4.9 volts.
Any logical solution or idea would be appreciated. Thanks!

The concept is actually quite simple.
You need to record the time when the signal goes high, and record the time when it goes low. The pulse width is the difference between the two times.
Yes, you can do it with interrupts, but you don't need to if you're not trying to do anything else at the same time.
A simple polling code could be something like this:
while (digitalRead(pin) == LOW); // Wait for input to go high
unsigned long startTime = millis(); // Record start time
while (digitalRead(pin) == HIGH); // Wait for input to go low
unsigned long endTime = millis(); // Record end time
unsigned long pulseDuration = endTime - startTime;

You basically sit doing nothing until the leading rising edge of your pulse.  You then record the time, and again sit doing nothing - this time while looking for the trailing falling edge of the pulse.  Then record the end time and subtract the two.

I understand the concept but can you please suggest some ways to do it? I'm not an expert in Arduino programming. I'm helping my teacher in her project. Please suggest the simplest method as no other processing has to be done when the pulse duration is being calculated.

I am on my phone at the moment. I can post some sample code later on.

Thank you very much. I'll try this code and let you know if it works.

Problem solved! My professor is satisfied with the result. You're the best! Thanks.

Here is some code I used to time a ball running down a ramp:
const byte LED = 12;
const byte photoTransistor = 2;

unsigned long startTime;
volatile unsigned long elapsedTime;
volatile boolean done;

void ballPasses ()
{
  // if high, start timing
  if (digitalRead (photoTransistor) == HIGH)
    {
    startTime = micros ();
    }
  else
    {
    elapsedTime = micros () - startTime;
    done = true;
    }

  digitalWrite (LED, !digitalRead (LED));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ("Timer sketch started.");
  pinMode (LED, OUTPUT);
  attachInterrupt (0, ballPasses, CHANGE);
}

void loop ()
  {
  if (!done)
    return;

  Serial.print ("Time taken = ");
  Serial.print (elapsedTime);
  Serial.println (" uS");
  done = false;
  }

Using micros() here is probably overkill, but that should be good for an interval up to 71 minutes.

An interesting code. Nice use of the flag 'done'. Thank you very much!

Hi @Nick-Gammon. I'm not sure it is important to mention but without timer rollover detection this code should only be used to measure events less than 70 minutes. (Did I do the math right on the rollover frequency?)

Well, I mentioned above that should be good for an interval up to 71 minutes. Yes, the rollover time is 71.58 minutes.


text:
High power consumption during power down mode
I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).
avr/power sketch:
#include <avr/power.h>
#include <avr/sleep.h>

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

  // Ensure no floating pins
  for(i=0; i<20 ; i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  // Power-down board
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();

  // Disable ADC
  ADCSRA &= ~(1 << ADEN);

  // Power down functions
  PRR = 0xFF;

  // Enter sleep mode
  sleep_mode();
}

void loop()
{
}

rocketscream/Low-Power sketch:
#include <LowPower.h>
void setup() {
}

void loop() {
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}

How are you powering it?

Using a 5V YwRobot breadboard power supply with VCC pin or a 9V battery with the RAW pin. Both are the same.

Are you measuring the current before or after the breadboard power supply?

After. Meanwhile I realized that the power led is always on even when the board is sleeping so I guess thats causing the power usage. I'll try to remove it and test again.

There is also a voltage regulator on that board, that has some quiescent current.

All I/O pins must be outputs and not driving a load OR inputs and terminated to high or low.

See Power saving techniques for microprocessors. The first things I would get rid of are the LED and the voltage regulator.

I tried your first sketch on my "bare-bones" board.

With the sketch exactly as written, it used 197 µA.
I wondered why it was that high, so I commented out this line:
  Serial.begin(9600);

That reduced consumption to 122 nA.
See Power saving techniques for microprocessors.
You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.
Of course, if you need the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.


text:
Convert ASCII output to human readable form and assign to a variable
I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.
byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

Serial output
read block: 1234567890123456

49505152535455565748495051525354

Any help please.

What do you mean "assign that to a variable"? It is in a variable already or you wouldn't be able to print it. It looks like the variable is called readbackblock.

I want to convert this ASCII 49505152535455565748495051525354 number to this 1234567890123456. I can do that on the Serial.write(), but what I wan't is to send the output to some other without printing on the Serial.

@Majenko thank you very much, that did the trick :) (Y)

I don't think it is possible.
The Arduino is 8-bit microcontroller, and can't handle integers larger than 32-bit. The maximum value for a unsigned 32-bit integer is 4294967296. This is a smaller number than your readblock, so it wil never fit.
If you want to do this with smaller numbers, you can use these 2 function:

atoi -> convert char array to integer
atol -> convert char array to long integer

Can't handle is a bit of a long bow to draw. I have a sketch here that calculates 3^160 = 21847450052839212624230656502990235142567050104912751880812823948662932355201 - now that's quite a big number. The issue isn't the size of the number.

The issue isn't how to "assign to a variable". The issue is something else. Perhaps the question could be clarified?

I want to convert this ASCII 49505152535455565748495051525354 number to this 1234567890123456. I can do that on the Serial.write(), but what I wan't is to send the output to some other without printing on the Serial


text:
How to send arduino data to php code
I'm new to arduino. I'm doing a project where I need to send a RFID UID to php code. The UID will be detected by the arduino and the rest will happen at the php side. for that I need to get this UID at oho side. I'm using RFID-RC522 and arduino mega 2560. how can I do this?
also I found couple of posts about ethernet. is it the only solution for this? if I use an ethernet shield will it block any ports which I'm using on arduino for connecting the RFID things?
thank you

Welcome to SE:Arduino.
Shields are usually designed so that the pins are still fully accessible.  The shield has a set of male connectors on the underside and female connectors (same as your Arduino) on the top side.  Just Google a pic of a shield and you will see what I mean.
Ethernet is not the only choice, there is Wi-Fi, Bluetooth, NFC, radio and probably a point to point light link.  What ever communication method you select, you would need to use HTTP POST messages to your server, so your server will have to implement a REST or SOAP interface. (There are probably other ways, but I'm not a webbie so you will need to ask them on the correct SE forum)
Once you have created your message on the Arduino you send it to your shield, probably by a function call or over a serial interface.  You'll get an OK back and all is good.
To find code that does this, just search, someone will have written and example, Adafruit and the Arduino.cc sites are good places to start.

I checked about the ethernet shield from following link https://www.arduino.cc/en/Main/ArduinoEthernetShield but there, they are mentioning that "Arduino communicates with both the W5500 and SD card using the SPI bus (through the ICSP header). This is on digital pins  50, 51, and 52 on the Mega. Pin 10 is used to select the W5500 and pin 4 for the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, 53 must be kept as an output or the SPI interface won't work." But I'm using the same set of ports for the RFID.. What is the solution?

If you can use Wi-Fi, I suggest you to use ESP8266-01, it's cheap and usefull ! With this chip you can send all data to your server!

You could probably do every thing on an ESP8266-12, twice as much processing power, loads more memory.  The only real draw back is five less analog ports, but that's what I2C ADCs where invented for :)

There is a lot of WiFi and ethernet shields, most of them(if not all) will not block your RFID especially if you use Mega2560. You must have a network connection for talking with php server, so YES, you need WiFi or ethernet shield.
Hope i'll help.
Yoav


text:
Reset and Remove Arduino ATmega328P?
So I have 2 Arduinos, and im wanting to remove the chip from one and reset it to like it came from the factory and then breadboard it and attempt to program it using an AVR programmer (Or maybe an Arduino AS a programmer).
Why? Mainly because I want to make sure I can and understand how to program the chips when I order them standalone and on a breadboard.
Is this possible? I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip?
Thanks!

You don't have to do anything. The first time you try to upload a program with an external programmer you will overwrite what was on the atmega

Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.
You can use the Arduino environment, upload facility, and board to learn low-level AVR programming.
Just because the Arduino helper functions exist it doesn't mean you actually have to use them.
The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.
If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.

Cool! So.... I just upload to the Arduino like it was a breadboard, and the arduino bootloader will be overwritten like normal?

The ICSP port is no different to using ICSP on the breaboard. You do exactly the same things. You can (with care) tweak your fuses to suit how you want to work, and flash whatever you want to flash.

+1 This is a great way to get into embedded for anyone coming from a software background.

"and im wanting to remove the chip
from one and reset it to like it came from the factory "
"Is this possible? "
Yes you can rewrite the atmega328 (used or blank) to reset arduino  to factory condition.
Yes you can use arduino as a programmer as other answer before implies.
If you are using blank new atmega328 you burn new bootloader from arduino IDE to make
factory reset arduino uno.
"I imagine the Arduino bootloader will be on the
 chip and the fuses will be different, but can I over-write them if
I decide to just program it as a standalone AVR chip? Is this possible?"
The arduino is a microcontroller development board which of course means
you can make the arduinos atmega 328 as standalone on breadboard; in addition to
that you can change the fuses to work with different speed crystals-which is what
 you seem to be asking.

The thing is im wanting to get away from the arduino environment completely, and run it as an AVR chip on it's own (and only using AVR commands with the AVR IDE)

What you trying to do  on AVR that cant be done with an Arduino?

Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc..

If your just using it to learn AVR  then you can use a cheap attiny 13 for one ore two dollars you can get 2 or 5 attiny 13a chips-that maybe a good idea for you. But if you have something more specific in mind-which you dont state in the question- then maybe you need a different atmel chip

I have a sketch that uploads data to various Atmega chips (including the 328P).
Even without an SD card attached you can do things like erase the chip and set fuses. So what I would do is erase the chip (thus the bootloader and any other code are gone), and then set the fuses to the factory defaults.
For the Atmega328P I believe these are:

Low: 0x62
High: 0xD9
Extended: 0xFF
Lock: 0xFF

Source: http://www.engbedded.com/fusecalc

You can initialize any Arduino compatible MCU easily, the procedures are well documented on the Arduino website.
There is even documentation to allow you to build based on the ATMega8L for a minimal system with no external crystal oscillator. This is a little harder to do, but not much.

I guess the thing is, im not going to be using the arduino system to program it AT ALL, im going straight AVR.

@msmith1114. If you remove the Arduino bootloader you will need either an ICSP or HV programmer.Just go to Atmel and download their tools, their development environment will default all the fuses.


text:
DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V)
I am facing one problem. I have code which read temperature and humidity using DHT11 sensor. I uploaded following code using Arduino via USB serial, I can read values of temp, humidity. Values are being read as long as Arduino is connected to same laptop via USB.
TEMPERATURE AND HUMIDITY are being read as 0 when I power on Arduino using DC12v, 700MA adapter.
I want to deploy Arduino with DHT sensors connected with it in Greenhouse to read greenhouse environmental condition but when I power on using DC adapter or battery, it is giving "0" output.
PLEASE HELP TO SOLVE THIS PROBLEM.
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

is 12v too high for the dht? why not just use 5v if it works?

This 9v to 12v dc adapter is not fed to DHT. This adapter is connected to DC adapter jack of Arduino. I am giving 3.3v to 5v to DHT correctly.

where does the 5v come from?

I have supplied 3.3v to 5v to DHT from another Arduino which is USB powered from PC. I am using Analog port A1 and DHT library from this link github.com/adafruit/DHT-sensor-library. Is this anything to do with analog port but it reads values when connected to USB ?

any suggestions ?

You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.
I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/

I am publishing these values via Ethernet to webserver. With USB connected to PC where I have uploaded the code from, it can send proper values of temp, humidity to webserver but when I power on using dc adapter, it just publishes "0" values of both temp and humidity.

I am using Analog port A1 and DHT library from this link https://github.com/adafruit/DHT-sensor-library. Is this anything to do with analog port but it reads values when connected to USB ?

any suggestions?

When the Arduino runs at 5V, it runs at 5V, no matter where that 5V comes from. The only difference is the voltage regulator. Do you have an Ethernet Shield ? That requires some current. The voltage regulator might get too hot and lower the current. Could you try a 7.5V power supply instead ?

I am using Ethernet Shield and dc adapter i have used is 9v, 750ma. Is this not ok ? and one more problem is that even if I connect USB from another PC, arduino read temp/humid as "0" only.


text:
Power consumption in Arithmetic Operation in Arduino UNO
I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.
Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

Did you try dividing?

I very much doubt it will be measurable compare to everything else going on in the chip.

Arduino is 8-bit microcontroller run by 8 MHZ clock frequency. So, to determine the period of the microcontroller clock, use equation as below:
Period (T) = 1/f = 1/ (8*10^6) = 0.125µs
Execution time (t) = C * T = 2 cycle * 0.125µs                                                                 Energy (E) = V * I * t = 5.5 6mA(from above fiigure) * 20.125µs                                                                                Please help me to correct if that above concept is correct or not

I think you'll find the Uno runs at 16MHz, not 8Mz, and 5V, not 5.5V.

Okay...if I change that ...everthing else is ok ?

Well, it doesn't tell you how much power the multiply operation uses, only how much power is used by the entire chip during the time it takes to execute a multiply operation.

I think that should be fine.Basically, I need to calculate the energy consumption for my encoder which has few multiplication operation and addition operation. Similarly I can calculate for addition too.

Did you read about what the "P" stands for in ATmega328p? PicoPower. The chip energy consumption depends on frequency and voltage (as in the diagram above). As most hardware design consumes energy on transitions it is not realistic to try to isolate the energy requirements for the instruction set (the processor core) as there are so many other activities (transitions) going on, e.g. clocks, timers, bus, etc.

The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.
The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.
Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

Addition
Test sketch
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo += 42;
  }

Generated code
  a6:   80 91 00 01     lds r24, 0x0100
  aa:   90 91 01 01     lds r25, 0x0101
  ae:   8a 96           adiw    r24, 0x2a   ; 42
  b0:   90 93 01 01     sts 0x0101, r25
  b4:   80 93 00 01     sts 0x0100, r24
  b8:   f6 cf           rjmp    .-20        ; 0xa6 <main+0x10>

Measured consumption
I measured an average of 7.00 mA.

Multiplication
Test sketch
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo *= 42;
  }

Generated code
  a6:   4a e2           ldi r20, 0x2A   ; 42
  a8:   20 91 00 01     lds r18, 0x0100
  ac:   30 91 01 01     lds r19, 0x0101
  b0:   42 9f           mul r20, r18
  b2:   c0 01           movw    r24, r0
  b4:   43 9f           mul r20, r19
  b6:   90 0d           add r25, r0
  b8:   11 24           eor r1, r1
  ba:   90 93 01 01     sts 0x0101, r25
  be:   80 93 00 01     sts 0x0100, r24
  c2:   f2 cf           rjmp    .-28        ; 0xa8 <main+0x12>

Measured consumption
I measured an average of 6.32 mA.

Conclusion
I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.
Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).
I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?
Update
As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.

It is worth noting that, after 14 iterations, foo is zero in your multiplication test. Also, this test spends 47% of its time doing memory access, v.s. 67% for the addition test. I would expect memory accesses to cost more energy than arithmetics, as you are loaded by the stray capacitance of the whole data bus. But then, if you only read and write zeros, you never charge that stray cap.

@EdgarBonet Good catch! See amended answer.

Why not just measure the current drawn by the board and an empty loop vs. a loop that does some multiplication? (other than 1,2,4,8..)

Is there any simpler way to measure current? I have digital USB multi-meter   purchased from http://www.ebay.ca/itm/like/172750787230?chn=ps&dispItem=1. I am powering from the USB port of this usb multimeter adapter but current is always same in all cases. Please let me know.

That device can only measure current in 10mA increments. You probably need something that can measure uA or better. A decent VOM or a bench top multi meter for example.

Okay. What will be the probe pins in Arduino Micro-controller in case we have to use multi meter othan USB multi-meter?

Use the 5V supply pin and connect the meter is series.

you mean 5V pin of arduino to multimeter's +ve terminal and GND of Arduino to multimeter's GND right?

Like this Better yet, google 'how to measure current' before you break something.

SO, if I measure current at 5V pin of arduino using multimeter (in range of micro amper), then I can compute the power consumption as below. Is this understanding correct? Arduino Uno R3 run by 16 MHZ clock frequency. So, to determine the period of the microcontroller clock, use equation as below: Period (T) = 1/f = 1/ (1610^6) = 0.0625µs Execution time (t) = C * T = 2 cycle * 0.0625µs Energy (E) = V * I * t = 5(measure current at 5V) * (2*0.0625)µs

I could NOT read micro ampere current at 5V power point. While measuring current via digital multi-meter, the mills-ampere current is showing reading as "1." So, in the equation E=V * I t (E = V * I * t = 510mA * (2*0.0625)µs, if I put I as 10mA, does that mean current taken by entire chip not Arithmetic operations, right?

Is there any way to determined the current or energy consumed while performing instruction sets (e.g. addition, multiplication, subtraction etc) in ATMega328P?


text:
Extracting char array out of function
I have a array called Table1 witch contains '1','2','3','4'
I do not want to work with global variables
I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1
This is the program i wrote:
void setup()

{
  Serial.begin(9600);
}

void loop()
{
  char tabel1[4] = {'1','2','3','4'};
  int i;
  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }

  tabel1 = Change(tabel1);

  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }
}

char Change(char tabel2)

{
  tabel2[0] = 'n';
  tabel2[1] = 'b';
  return tabel2;

}

This is the error i'm getting:
In function 'void loop()':
testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
tabel1=Change(tabel1);
^
In function 'char Change(char*)':
30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return tabel2;
^
exit status 1

[Error] Exit with code=1

Did you mean table or tabel??

I'm dutch and table in dutch is tabel so yeh XD

You should read something about C arrays and how they work.
Anyway, if you use:
  Change(tabel1);

// ...

void Change(char * tabel)
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

It'll change passed array because it's passed as pointer to the first element of tabel1.

In c an array's name is effectively a pointer to the start of the memory location where the array is stored. You have to be careful, if you pass an array to a function that function will have no knowledge of the array size. If there is a risk of the size being unknown you normally pass a second parameter, the size of the array. In this case we will assume the array passed to change is always at least 2 chars long and risk a crash if it isn't.
At the most simple level your change function becomes:
void Change(char tabel[])
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

and the line to call it is:
Change(tabel1);
Notice how there is no return type or return value. We were passed a pointer to where the array is in memory. When we make changes to the values we are changing the original array directly. The old values are lost.
The function:
void Change(char *tabel)
{
  *tabel = 'n';
  *(tabel+1) = 'b';
}

Is functionally identical to the one above only it is explicitly using a pointer rather than an array.
One thing you need to get used to in c is that an array is not a type of variable, it's a collection of variables. As such normal variable operations don't work on them.
e.g. array1 = array2 does not set the contents of array 1 to being the same as array2. It sets the memory address where array1 is stored to being the same as the memory address that is used for array2. The original memory used to store array1 is no longer accessible by the program and is now unusable. This is a bad thing.
Similarly if (array1 == array2) doesn't compare the contents of the two arrays, it compares their memory addresses.


text:
In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines
    #define LS 2      // left sensor
#define RS 3      // right sensor

/*-------definning Outputs------*/
#define LM1 4       // left motor
#define LM2 5       // left motor
#define RM1 6       // right motor
#define RM2 7       // right motor

void setup()
{
  pinMode(LS, INPUT);
  pinMode(RS, INPUT);
  pinMode(LM1, OUTPUT);
  pinMode(LM2, OUTPUT);
  pinMode(RM1, OUTPUT);
  pinMode(RM2, OUTPUT);
}

void loop()
{
  if(digitalRead(LS) && digitalRead(RS))     // Move Forward
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, HIGH);
    digitalWrite(RM2, LOW);
  }

  if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
  {
    digitalWrite(LM1, HIGH);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }

  if(!(digitalRead(LS)) && !(digitalRead(RS)))     // stop
  {
    digitalWrite(LM1, LOW);
    digitalWrite(LM2, LOW);
    digitalWrite(RM1, LOW);
    digitalWrite(RM2, LOW);
  }
}

i got this code from a site.My doubt is if the left sensor is not reading means it has value of zero hence it is on black line and the right sensor is on white line.Then it should move to left side itself.BUt the program says it should moves to right.Iam a beginner.Please help me to clear my doubt

This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.
If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.


text:
Deprecated Conversion error
I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming
How to remove it?
C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino: In function 'void updateState(byte)':
C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are const char* and the function parameters are declared as char*.
The correct way to fix this would be to update DisplayInfo() so that the parameter types are const char*. The dirty fix is to cast the parameters in the call.
   DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

But I would not recommend that.
Cheers!

The correct way is always the better and the header of DisplayInfo() should be changed to use const keyword in parameters. If code is third party, author/maintainer should be also informed to patch it. Good answer @mikael-patel :)

An alternative is to declare some string constants and then pass the variable names into the function. i.e. const char cRFIDScanner[] = "RFID Scanner"; const char cStarting[] = "Starting up"; DisplayInfo(cRFIDScanner, cStarting, HIGH, HIGH);


text:
How do I use a photodiode for arduino?
I am doing a project that requires me to program an arduino to sense changes of a steady stream of light due to the scattering of that light. If the phootodiode does change its resistance to the current, then a flap will turn a certain number of degrees. I'm not sure how to operate a photodiode, but know the basics of how it works.
The apparatus is designed to increase the operating life of a solar panel on Mars. When dust from a dust storm collects on its surface, a photodiode will detect the change in light and change its resistance to a current running through it. Then a flap connected to the solar panel will close to cover the solar panel. I'm using Hitec HS-311 Standard servo to rotate  the flap, but I've had some problems operating it.

A photodiode does not change resistance. It generates a tiny current when light strikes it.

http://electronics.stackexchange.com/questions/73732/how-to-use-sfh235-ir-photodiode-correctly

photodioides are rare and relativily expensive; you probably want a light-dependent resistor (cds), which makes for easy analog-input voltage-divider circuits. Or a phototransistor, which works like a regular transistor and can control a digital input easily.

try to use an opamp to create a voltage output from the diode. you can then adc that voltage output from the mcu.

Could you be more specific please?


text:
What's the difference between analogWrite and digitalWrite?
As the title states. What's the difference between the two?
analogWrite(pin,0-255) vs digitalWrite(pin,LOW-HIGH)

I don't mean to be rude but what was confusing about this in the documentation at arduino.cc or included with the IDE?

digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.
analogWrite can vary by the type of output used.
If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -
    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while
    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time
When applying analogWrite to a DAC pin (available on some boards, like the DUE or MEGA)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value
For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]
    analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-
    analogWrite(DACpin,127)

Will cause the specified pin to output 1.35v

No, there is no DAC on the Mega.

you are correct, answer edited to reflect this.

Great. I took the liberty to make the edit more concise.

I believe there is a "maxanalog" define or constant, to provide better compatibility with other platforms. The esp8266 has an analogwrite that can range from 0 to 1024. *I've scratched some hairs out trying to find why my RGB led controller wouldn't be as bright with the same code, thought it was due to the difference in power or voltage, but I used an MOSFET with suitable (gain?) factor. It was simply on for (1024/256) of the time.

analogWrite(): The analogWrite() method sets the value of a PWM output pin. The analogWrite() is on a scale of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half the time).

Syntax: analogWrite(pin, val)
Where,
pin: the PWM output pin number.
val: int value of duty cycle between from 0(always off) to 255(always on)
Example Code:
int outLed = 10;  //LED connected to digital pin 10
int value = 0;    //variable to store the read value
int analogIN = 3; //input pin

void setup()
{
  pinMode(outLed, OUTPUT); // set the PWM pin as OUTPUT
}

void loop()
{
  value = analogRead(analogIN); // read the value of analogIN (values between from 0 to 1023)
  analogWrite(outLed, value/4); // sets the read value on outLed (values between from 0 to 255)
}

digitalWrite: The digitalWrite() method sets the value of a digital pin as HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
Syntax: digitalWrite(pin, val)
Where,
pin: the pin number
val: HIGH or LOW
Example Code:
int ledPin = 13;                // LED connected to digital pin 13

void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(ledPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(ledPin, LOW);    // sets the LED off
  delay(1000);                  // waits for a second
}

digitalWrite sets the output pin to either LOW or HIGH (where those voltages depend on the Vcc of the processor. For a Uno or Mega that would be 0V or 5V (or close to it).
Here's a screenshot of digitalWrite (LOW):

That is, the output pin is at 0V.

Now for digitalWrite (HIGH):
The output voltage is 5V.

analogWrite really should have been named PWMwrite since it configures the processor timers to output PWM (pulse-width modulation).
Let's try analogWrite(1):

You can see that the voltage level is 0V most of the time, and going to 5V for short periods. You also see that the frequency is 490 Hz which is what the reference page for analogWrite says it will be.

Zooming in:

The output is high for 8 µs, which is exactly 1/256 of 2048 µs which is the period of the timer. So, we have a duty cycle of 1/256 (0.39%).

Let's try analogWrite(127) - half-way from 0 to 255:

Now you can see that the output is HIGH exactly half the time, and LOW the rest of the time.

Let's try analogWrite(254):

This is the opposite of analogWrite (1). The output is HIGH all the time except for a brief period. Zooming in:

Now the output is off for 8 µs - compared to the earlier image where it was on for 8 µs.

analogWrite (0) is the same as digitalWrite (LOW).
analogWrite (255) is the same as digitalWrite (HIGH).
This is proven by the relevant code in wiring_analog.c:
if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}

Summary
analogWrite basically configures the hardware timers to output PWM. Once you do that the timer hardware outputs the requested duty cycle (from 0 to 255) where 0 is always off, 255 is always on, and some value inbetween gives you PWM (pulsed output).

For more information about the timers see my page about timers.

digitalWrite sets the pin to an high or low value that remains at exactly that value until digitalWrite is called for that pin again.
analogWrite sets the pin to have an oscillating value which has a pulse length based of the duty cycle specified as the second parameter.
So:
digitalWrite (5, HIGH);    // Pin 5 goes high
analogWrite (6, 127);      // Pin 6 oscillates regularly between 0v and 5v (or 3.3v) at about 250Hz.

digitalWrite set the specified pin to one of two states - HIGH/LOW
Where, HIGH = 5 V and LOW = 0 V
analogWrite Set the PWM value of PWM pin
(In Arduino UNO, PWM pins are 3, 5, 6, 9, 10, 11)
It will set the pin to a periodic high/low signal.
analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while
analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time

analogWrite():
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.
For details visit: https://www.arduino.cc/en/Reference/analogWrite
analogRead():
Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can be changed using analogReference().
For details visit: https://www.arduino.cc/en/Reference/analogRead

So what's the difference between analogWrite(X, 255) and digitalWrite(X, HIGH)? Probably nothing, except perhaps the processor has to do some extra stuff to work out that it doesn't need to use PWM, and also style.

Another subtle difference between analogWrite(pin, 255) and digitalWrite(pin, HIGH) is that digitalWrite requires you to set the pin to output using pinMode. analogWrite sets the pin to output on each call, which makes it slower and might ruin the code which uses the same pin alternatively as input and output, and relies on the fact that writing to the input pin using digitalWrite doesn't switch it to output.

authors: Максим Бредерман


text:
Working or functionality Serial.begin(9600)
In recent practice, I found out some new things.
Serial.begin(9600);
What is mean of this line of code?
Why here, we always write 9600?
And can we write manually number means instead of 9600 let's say 10000?

RTM.  If you go to https://www.arduino.cc/en/Reference/HomePage and then fin Serial.Begin() https://www.arduino.cc/en/Serial/Begin you will find out what it means.  Also you see the meaning of all the function calls.

Serial.begin(9600);
What is mean of this line of code?
Serial.begin(9600) doesn't actually print anything.
If you want to print "Hello world!" to the serial monitor then you have to use this line of code. Rather it initializes the serial connection at 9600 bits per second.
It is used for kind of handshaking means both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.
Why here, we always write 9600?
And 9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Ardunio to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Ardunio IDE's serial monitor) to the same speed in order to see the data being sent.
And can we write manually number means instead of 9600 let's say 10000?
No, we can't write. There is a specific baud rate available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.

Serial.begin(9600);

This line starts Serial communication with a baud rate of 9600. Serial communication is used to transmit data between your application and external systems (including your PC, other Arduinos, sensors, and other ICs).
Most of the time this is included to allow the application to output information via the Serial Monitor when connected to you PC.
Documentation for this is here:
https://www.arduino.cc/en/reference/serial
From the documentation: "For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200."
- source

It's worth noting that on boards with a "direct" USB connection (such as the Leonardo, Micro, Teensy, Lenny, Fubarino, etc) the baud rate is actually meaningless.


text:
Working or functionality of pinMode(), digitalWrite() and digitalRead()
I'm a newbie in Arduino. I find out a couple of examples.
Here, below arduino simple code I just uploaded.
Here, what is functionality or working of pinMode, digitalWrite and digitalRead ?
const int kPinLed = 7;
const int kPinBtn = 8;

void setup()
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)
  {
    digitalWrite(kPinLed, HIGH);
  }
  else digitalWrite(kPinLed, LOW);
}

pinMode https://www.arduino.cc/en/Reference/pinMode

digitalWrite https://www.arduino.cc/en/Reference/digitalWrite

digitalRead https://www.arduino.cc/en/Reference/DigitalRead

And all you need to know - a tutorial https://www.arduino.cc/en/Tutorial/DigitalPins, have fun.

How a GPIO pin actually works in output mode: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/ (other modes to follow when I have written them).

Welcome to the world of Arduino!
To start off, the Arduino website has excellent descriptions of its various API functions, in your case -
https://www.arduino.cc/en/Reference/pinMode
https://www.arduino.cc/en/Reference/DigitalWrite
https://www.arduino.cc/en/Reference/DigitalWrite
Now to answer your question:
pinMode determines whether a specified pin behaves as input or output - does it read a signal to the Arduino (read from a a sensor, for example) or does it output to another component (a led to light it, a motor to move it). It achieves this by changing the impedance on the pin- high impedance for input, low for output.
IINPUT_PULLUP means both setting the pin to input mode, while 'pulling up' the input to be high when it is not explicitly low by an external component (whatever is connected to the pin)
  //configure the pin somePin to behave as output
  pinMode(somePin, OUTPUT);
  //configured the pin to behave as input, and 'pullup' the input to HIGH
  pinMode(somePin, INPUT_PULLUP);

Once you have set a pins mode to be input/output, you can read or write from it, depending on its mode.
If you configured a pin to be in input mode, you can use digitalRead
//read the value from someInputPin and store it in the variable 'num'
int num = digitalRead(someInputPin);

If you configured a pin to be in output mode , you can use digialWrite
//write the value from 'num' to someOutputPin, and by extension whatever connected to it
int num = HIGH;
digitalWrite(someOutputPin,num);

{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

This block of code used to define mode of Pin i.e. making pin as Output pin or Input pin.
if(digitalRead(kPinBtn) == LOW)
{

}

This block of code is used to read value from defined digital pin either High or Low. And in return will give pin state High or Low. For example if we want to make LED ON which is connected to one of digital pin of Arduino at certain condition, we will define that pin under above block of code and can read state of that pin as High or Low.
 {
   digitalWrite(kPinLed, HIGH);
 }
 else digitalWrite(kPinLed, LOW);

This block of code is used to make Pin state High or Low i.e. Under certain condition this function will make pin state either High or Low.
To learn more, visit......
PinMode Click here
DigitalRead Click here
Digital Write Click here

Very good question for every beginner. Let me explain.
pinMode() : This function set the functionality of pin. Means either INPUT or OUTPUT or INPUT_PULLUP.
INPUT use when you connect your arduino to the sensor.
OUTPUT use when you connect your arduino to LED, motor etc.
INPUT_PULLUP use when we require internal pull-up. For example, if we connect a pushbutton to our arduino then we require some pull-up resistor. Then this thing can be done by this INPUT_PULLUP. So we don't require any resistor in circuitry.
Now depend upon your circuit requirement you have to use proper pinMode.
Syntax: pinMode(pin, mode)
Where,
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP.
You can see this thing in your code.
void setup()
{
  pinMode(kPinLed, OUTPUT);       // LED as OUTPUT
  pinMode(kPinBtn, INPUT_PULLUP); // Push Button as INPUT with pull-up.
}

digitalWrite(): This function set pin states either HIGH or LOW. Here, 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
Syntax: digitalWrite(pin, value)
Where,
pin: the pin number
value: HIGH or LOW
Now, again in your code.
digitalWrite(kPinLed, HIGH); // Pin set as HIGH

digitalWrite(kPinLed, LOW);  // Pin set as LOW

digitalRead(): This function use to read the value from a specified digital pin, either HIGH or LOW.
Syntax: digitalRead(pin)
Where,
pin: the number of the digital pin you want to read (int)
And this thing in your code looks like.
if(digitalRead(kPinBtn) == LOW) // Check pin states : LOW or HIGH
{
  //Your code...
}

PinMode sets the mode or function of the pin, like input (when you connect it to a sensor), or output (when you connect it to a LED for example). There are also some variances (like pullup/pulldown for special cases).
In practice, when you set the value to LOW, 0 V will be put on the signal, and 5 V will be put when it is HIGH (at least on an Uno).
PinModes are normally set during setup (once), and DigitalRead/Writes in the loop since you want to change it dynamically.
Btw, the last pat of the example can be better written as:
digitalWrite(kPinLed, digitalRead(kPinBtn) == LOW ? HIGH : LOW);

The ? operator (called ternary operator) checksk if the condition (digitalRead(kPinBtwn) == LOW is true, if so it will use the value behind ? otherwise the vvalue after : is used).

digitalWrite(kPinLed, !digitalRead(kPinBtn)); works also fine.


text:
L298 with stepper.h disable break
I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this.
Do you have an idea ?
My code is simple :
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

I took it from here : https://coeleveld.com/arduino-stepper-l298n/
Thanks !

There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.
There's nothing to stop you just placing those same IO pins in a different state - the library won't care.
void sleepStepper() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
}

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).
Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.

Oh ! I thought that the library will block the pins ! Thank you.

@LelaidierLucas Nah - it just performs a sequence of digitalWrite() calls.


text:
Controlling DC motor using the Servo pins
I have a L293D motor shield for arduino uno. It has capability of controlling 2 servo motors and 4 DC motors. But I want to control 5 DC motors for my project. So my question is can I use the 3 pins that are there in motor shield ( to control servo motors) for controlling a DC motor? Or any other solution if any without using any other hardware?

No. A servo motor has its own built-in driver and you just send a low-level PWM signal to control it. That cannot directly drive a DC motor.
If you want more DC motors you will need more DC motor driving hardware.  For simple speed control in one direction that could be as simple as a NPN transistor (or N-channel FET), a base resistor, and a flyback diode (just like driving a relay). For direction control you will need a H-bridge like the L293D (which incidentally is a very poor choice of driver by today's standards - very inefficient and lossy. I wish people wouldn't persist in selling it.)


text:
Serial communication mac to Digispark ATtiny85
I want to use the Arduino IDE serial monitor with my Digispark ATtiny85 over USB.
I can without problems upload this code(Digispark CDC example):
#include <DigiCDC.h>
void setup() {
  SerialUSB.begin();
}
void loop() {
  SerialUSB.println(F("TEST!"));
 //SerialUSB.delay(10);
}

In a terminal, I can confirm, that it indeed creates a new devise:
ll /dev/*usb*
crw-rw-rw-  1 root  wheel   21,  89 27 Sep 10:36 /dev/cu.usbmodem1411
crw-rw-rw-  1 root  wheel   21,  88 27 Sep 10:36 /dev/tty.usbmodem1411

When trying to start the Arduino serial monitor, I get the error:
 Error opening serial port '/dev/cu.usbmodem1411'. (Port busy)

I have confirmed that there are no open files or processes using the USB port. I have the same problem trying to use cu or screen in the terminal.
I have googled the problem, and found that several people has the same problem on new mac computers, but I have not been able to find a solution. -any ideas?

Digispark Rev3 (Chinese clone - with bootloader firmware 1.6 (1.06))
Arduino IDE 1.8.7
Mac OSX High Sierra 10.13.6

I don't know about OS X, but I do know that the ATTiny85 doesn't have a USB interface - so it's all done in software. TBH you're lucky it gets as far as it does. I have never been a fan of bit-banged USB like that. It's nasty.

@Majenko I can use the Digispark as a USB HID keyboard, so the banging of the bits do work :o)

You can only bit-bang low-speed USB. Low-speed is only intended for use with keyboard and mouse. CDC/ACM really requires full- or high-speed, so trying to use it over low-speed is "undefined".

@Majenko: I appreciate the support. I would be happy with any low speed way of sending a string from my computer to the Digispark. If it is not possible, do you know of a chip, that I can add to the ATtiny85 to give it hardware USB?

Unfortunately, it's a known issue on mac os that has no solution at the moment. digiUSB is mentioned on one forum as a workaround. However, sending and receiving is done via python scripts with this method of communication. If you want hardware USB in the same board format, you can try ATMega32U4-based "beetle" boards available for ~5 USD on ebay.

Don't use DigiUSB! It's deprecated using old usblib0 (new is libusb-1.0) and the highly dysfunctional libusb-win32. Also if you use that, you have to be careful not to overwrite the internal V-USB, perhaps by disabling your own after some time. Apparently DigiCDC is the followup of that.

@not2qubit: I do not understand. What is DigiUSB? How am I using it? Actually I do not understand what you are writing at all. What am I doing wrong, and what can I do instead?

From DigiUSB: This library has been deprecated in favour of: DigiCDC. With DigiCDC the Digispark will show up as a COM port and the Arduino Serial monitor can be used normally. DigiUSB requires communication to the Digispark through a seperate application.

@not2qubit: Ok - I have now come to the conclusion, that you have not read my question at all, and you have no idea about the problem on a mac.

Oh, sorry, I was merely responding to the comments above. Do you have lsof on the mac? If so try lsof |grep "/dev/cu.usbmodem1411". It should in theory show you what process is using that device. You can also try various options to ps.

SoftSerial and a real serial port on the mac will work. Or if you are careful use the DigiKeyboard and print the debug to the HID keyboard REMEMBERING to switch to a notepad equivalent window on the mac to receive and display the debugging text and not have it overwriting the arduino sketch by mistake.
DigiCDC is a kludge that does not work properly on modern operating systems sorry!

Thanks for your input, but I do not understand what you mean by " ...a real serial port on the mac ..."? Do you mean something like this https://plugable.com/2011/07/12/installing-a-usb-serial-adapter-on-mac-os-x/ ?What debug are you referring to? HID works perfectly, but I want serial communication from and to the Digispark.

presumably no modern Mac has a builtin RS232 interface so you'd need a USB to RS232 interface yes like in that article you link to. There are a few common chips that are used in the devices PL2303, CH340/CH341, FT232RL and so on. There is a software serial emulation library that works on the Attiny85 digispark boards and uses 1 or 2 or the IO pins obviously there are certain limitations with software emulation but it does work adequately. Serial is often used to output debugging messages with arduinos when developing sketches.


text:
Writing to a SPI memory
Recently I salvaged a BIOS chip (EN25QH16) which has 2 Megabytes of memory (8192 pages, 256 bytes/page). I followed this instructables and it works. I double checked the opcodes because the code is for a Winbond chip, mine is Eon and of course, they're the same (standards?). All commands worked as it should. I modified the code that writes Hello World string to a page. I tried the command but it returns (from the memory) Hello Worlb. This is the snap of the serial monitor:

I erased the chip just to make sure and ran the command test_write (which I added). It wrote 48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00 which is in ASCII Hello Worlb and I don't know why that happened. Btw this is the modified code:
/*
    windbond_serial_debug.cpp
    A simple program for the Arduino IDE to help familiarize you with
    using WinBond flash memory; can also be used to download the entire
    contents of a flash chip to a file via a serial port interface.

    Important bits of the code: the low-level flash functions (which
    implement the timing diagrams in the datasheet), and a simple
    serial-port command interface that allows you to talk to your
    UNO with any generic terminal application (even the command line).

    Copyright 2014, Peter J. Torelli

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Revisions:
    rev 2 - 21-SEP-2014.
    User 'fiaskow' pointed out that driving the WEL instruction after
    program and erase w/o waiting for the op to finish may be corrupting
    execution. Removed this code (also not needed b/c the WEL is already
    cleared after page write or chip erase).
*/

#include <SPI.h>
// SS:   pin 10
// MOSI: pin 11
// MISO: pin 12
// SCK:  pin 13

// WinBond flash commands
#define WB_WRITE_ENABLE       0x06
#define WB_WRITE_DISABLE      0x04
#define WB_CHIP_ERASE         0xc7
#define WB_READ_STATUS_REG_1  0x05
#define WB_READ_DATA          0x03
#define WB_PAGE_PROGRAM       0x02
#define WB_JEDEC_ID           0x9f

/*
 * These global variables enable assembly of the user serial
 * input command.
 */
boolean g_command_ready(false);
String g_command;

/*
 * print_page_bytes() is a simple helperf function that formats 256
 * bytes of data into an easier to read grid.
 */
void print_page_bytes(byte *page_buffer) {
  char buf[10];
  for (int i = 0; i < 16; ++i) {
    for (int j = 0; j < 16; ++j) {
      sprintf(buf, "%02x", page_buffer[i * 16 + j]);
      Serial.print(buf);
    }
    Serial.println();
  }
}

/*
================================================================================
User Interface Routines
The functions below map to user commands. They wrap the low-level calls with
print/debug statements for readability.
================================================================================
*/

/*
 * The JEDEC ID is fairly generic, I use this function to verify the setup
 * is working properly.
 */
void get_jedec_id(void) {
  Serial.println("command: get_jedec_id");
  byte b1, b2, b3;
  _get_jedec_id(&b1, &b2, &b3);
  char buf[128];
  sprintf(buf, "Manufacturer ID: %02xh\nMemory Type: %02xh\nCapacity: %02xh",
    b1, b2, b3);
  Serial.println(buf);
  Serial.println("Ready");
}

void chip_erase(void) {
  Serial.println("command: chip_erase");
  _chip_erase();
  Serial.println("Ready");
}

void read_page(unsigned int page_number) {
  char buf[80];
  sprintf(buf, "command: read_page(%04xh)", page_number);
  Serial.println(buf);
  byte page_buffer[256];
  _read_page(page_number, page_buffer);
  print_page_bytes(page_buffer);
  Serial.println("Ready");
}

void delayed_read_all_pages(void) {
  delay(5000);
  read_all_pages();
  }

void read_all_pages(void) {
  Serial.println("command: read_all_pages");
  byte page_buffer[256];
  for (int i = 0; i < 4096; ++i) {
    _read_page(i, page_buffer);
    print_page_bytes(page_buffer);
  }
  Serial.println("Ready");
}

void write_byte(word page, byte offset, byte databyte) {
  char buf[80];
  sprintf(buf, "command: write_byte(%04xh, %04xh, %02xh)", page, offset, databyte);
  Serial.println(buf);
  byte page_data[256];
  _read_page(page, page_data);
  page_data[offset] = databyte;
  _write_page(page, page_data);
  Serial.println("Ready");
}

/*
================================================================================
Low-Level Device Routines
The functions below perform the lowest-level interactions with the flash device.
They match the timing diagrams of the datahsheet. They are called by wrapper
functions which provide a little more feedback to the user. I made them stand-
alone functions so they can be re-used. Each function corresponds to a flash
instruction opcode.
================================================================================
*/

/*
 * See the timing diagram in section 9.2.35 of the
 * data sheet, "Read JEDEC ID (9Fh)".
 */
void _get_jedec_id(byte *b1, byte *b2, byte *b3) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_JEDEC_ID);
  *b1 = SPI.transfer(0); // manufacturer id
  *b2 = SPI.transfer(0); // memory type
  *b3 = SPI.transfer(0); // capacity
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.26 of the
 * data sheet, "Chip Erase (C7h / 06h)". (Note:
 * either opcode works.)
 */
void _chip_erase(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_CHIP_ERASE);
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }
/*
 * See the timing diagram in section 9.2.10 of the
 * data sheet, "Read Data (03h)".
 */
void _read_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_DATA);
  // Construct the 24-bit address from the 16-bit page
  // number and 0x00, since we will read 256 bytes (one
  // page).
  SPI.transfer((page_number >> 8) & 0xFF);
  SPI.transfer((page_number >> 0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    page_buffer[i] = SPI.transfer(0);
  }
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.21 of the
 * data sheet, "Page Program (02h)".
 */
void _write_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_PAGE_PROGRAM);
  SPI.transfer((page_number >>  8) & 0xFF);
  SPI.transfer((page_number >>  0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    SPI.transfer(page_buffer[i]);
  }
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}

/*
 * not_busy() polls the status bit of the device until it
 * completes the current operation. Most operations finish
 * in a few hundred microseconds or less, but chip erase
 * may take 500+ms. Finish all operations with this poll.
 *
 * See section 9.2.8 of the datasheet
 */
void not_busy(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_STATUS_REG_1);
  while (SPI.transfer(0) & 1) {};
  digitalWrite(SS, HIGH);
}

/*
 * This handy built-in callback function alerts the UNO
 * whenever a serial event occurs. In our case, we check
 * for available input data and concatenate a command
 * string, setting a boolean used by the loop() routine
 * as a dispatch trigger.
 */
void serialEvent() {
  char c;
  while (Serial.available()) {
    c = (char)Serial.read();
    if (c == ';') {
      g_command_ready = true;
    }
    else {
      g_command += c;
    }
  }
}

void setup(void) {
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);
  Serial.begin(9600);
  Serial.println("");
  Serial.println("Ready");
}

/*
 * loop() dispatches the commands compiled by the serialEvent
 * parser callback. Some commands take multiple arguments, so
 * I have to split up the strings with some messy manipulation.
 */
void loop(void) {
  if (g_command_ready) {
    if (g_command == "get_jedec_id") {
      get_jedec_id();
    }
    else if (g_command == "test_write") {
      Serial.println("Custom command: test_write");
      _write_test();
      }
    else if (g_command == "chip_erase") {
      chip_erase();
    }
    else if (g_command == "read_all_pages") {
      read_all_pages();
    }
    else if (g_command == "delayed_read_all_pages") {
      Serial.println("Custom command: delayed_read_all_pages");
      delayed_read_all_pages();
      }
    // A one-parameter command...
    else if (g_command.startsWith("read_page")) {
      int pos = g_command.indexOf(" ");
      if (pos == -1) {
        Serial.println("Error: Command 'read_page' expects an int operand");
      } else {
        word page = (word)g_command.substring(pos).toInt();
        read_page(page);
      }
    }
    // A three-parameter command..
    else if (g_command.startsWith("write_byte")) {
      word pageno;
      byte offset;
      byte data;

      String args[3];
      for (int i = 0; i < 3; ++i) {
        int pos = g_command.indexOf(" ");
        if (pos == -1) {
          Serial.println("Syntax error in write_byte");
          goto done;
        }
        args[i] = g_command.substring(pos + 1);
        g_command = args[i];
      }
      pageno = (word)args[0].toInt();
      offset = (byte)args[1].toInt();
      data = (byte)args[2].toInt();
      write_byte(pageno, offset, data);
    }
    else {
      Serial.print("Invalid command sent: ");
      Serial.println(g_command);
      g_command = "";
    }
done:
    g_command = "";
    g_command_ready = false;
  }
}

byte data[sampleText.length()];, should be byte data[256];, as _write_page expects the page_buffer to be 256 bytes long. Also 48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00 isn't Hello Worlb but Hello Worl<null>b<etx><vt><null><vt><null>

@Gerben Hello Worlb is from an online converter but the Notepad++ conversion looks like yours.

Strings in C are terminated with a null byte - so the string "A" is in fact two bytes: the 'A' followed by a null.
Your _write_test() function counts only the characters in the string, and hence allocates one byte too few.  It should be:
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()+1];
  sampleText.getBytes(data, sizeof(data));
  // See text below before calling write_page()
}

But then we hit the issue of how much data write_page() will write.  It doesn't have any way of knowing how much data you are passing in - it just gets a pointer.  Looking at its implementation we can see that it writes exactly 256 bytes, so we need to pass in a buffer of 256 bytes.
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[256];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }

(If we pass in a smaller buffer we're leaving it up to chance what will happen.  The Arduino doesn't have much protection so probably you'll just write garbage, but maybe, just maybe, you'll get unlucky and some weird crash will happen.)

Yep with my code it writes some garbage (I converted the hex and there's some of it). Well, it works now. Thanks!


text:
Pin identification for a salvaged LCD
I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

i would try some of the LCD libraries, the ones people use for 5110 displays.

They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.
However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.

It's unlabeled, the silicon driver chip is on the glass covered by black silicone. I will try some LCD libraries. If there's a resolution mismatch, I will have to modify the library. A0 (and BL)is the only reason why I asked. Thank you


text:
Better way to remap 16-Key Touch keypad
I have written a code that remaps the buttons of TTP229 touch keypad which works as it is. Is there any way to optimize this code:
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SCL_PIN 11
#define SDO_PIN 12
#define I2C_ADDR    0x3F
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

byte Key;
String keyRemap[12][2] = {
    {"1","1"},{"2","2"},
    {"3","3"},{"5","4"},
    {"6","5"},{"7","6"},
    {"9","7"},{"10","8"},
    {"11","9"},{"14","0"},
    {"13","Clear"},{"15","Enter"}
};

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup()
{
    lcd.begin (16,2);
    lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
    lcd.setBacklight(HIGH);
    lcd.home ();

    pinMode(SCL_PIN, OUTPUT);
    pinMode(SDO_PIN, INPUT);
}
void loop()
{
    Key = Read_Keypad();
    if (Key != 0) {
        lcd.clear();
        lcd.setCursor (0,0);
        for (int x = 0; x < 12; x++) {
            if (Key == keyRemap[x][0].toInt()) {
                lcd.print(keyRemap[x][1]);
            }
        }
        delay(160);
    }
}
byte Read_Keypad(void)
{
    byte Count;
    byte Key_State = 0;

    for (Count = 1; Count <= 16; Count++)
    {
        digitalWrite(SCL_PIN, LOW);
        if (!digitalRead(SDO_PIN))
            Key_State = Count;
        digitalWrite(SCL_PIN, HIGH);
    }
    return Key_State;
}

What do mean exactly by "optimize the code"? Do you have problems with its speed, its size, or anything? What is your question really?

Is there any way to optimize this code:

Absolutely, yes. Don't use String for this, you are seriously wasting memory. Instead you can use a struct:
struct keymap {
    uint8_t code;
    const __FlashStringHelper *value;
};

const struct keymap keyRemap[] = {
    { 1, F("1") },
    { 2, F("2") },
    { 3, F("3") },
    { 5, F("4") },
    { 6, F("5") },
    { 7, F("6") },
    { 9, F("7") },
    { 10, F("8") },
    { 11, F("9") },
    { 14, F("0") },
    { 13, F("Clear") },
    { 15, F("Enter") },
    { 0, 0 }
};

void loop() {
    int Key = Read_Keypad();

    if (Key != 0) {
        lcd.clear();
        lcd.setCursor(0, 0);

        for (int x = 0; keyRemap[x].code != 0; x++) {
            if (Key == keyRemap[x].code) {
                lcd.print(keyRemap[x].value);
            }
        }

        delay(160);
    }
}

Will you stop posting faster than me :)

I can't help it if I had 2 coffees this morning :P

You could also fully populate the table with all possible answers and then this would remove the loop when looking for answers, but you would need to handle 4 and 12 specially.

It would remove the need for the struct entirely then - a simple 16-entry array. But where would the fun in that be?

@Majenko I used your code and I got an error

@conquistador Probably something odd with the Arduino IDE (that I never use) - some flag not being set or being set that shouldn't really be being set.


text:
ATtiny85 won't wake from sleep
My ATtiny 85 won't wake up!
The purpose of the device is to monitor a reed switch and give a 20 ms output pulse on every alternate positive-going transition of the reed switch input. The device should go to sleep after 30 s of inactivity. It should wake up on reed switch activity (rising or falling edge).
/*
          ATMEL ATTINY 85
              +-\/-+
        PB5  1|    |8  Vcc
        PB3  2|    |7  PB2 (INT0) reed switch input (1 MΩ ext. pull-up)
        PB4  3|    |6  PB1        output
        GND  4|    |5  PB0
              +----+
*/
#include <avr/sleep.h>
#include <avr/power.h>
#include <elapsedMillis.h>

const int hallPin = 2;            // Reed switch in this case.
const int magnetPin =  1;         // Output.
const long debouncing_time = 15;  // Debouncing time in milliseconds.

volatile int hallState = 0;       // variable for storing the hall counter
volatile bool hallMem = 0;        // One-shot memory.
volatile unsigned long last_micros;

elapsedMillis timer;

void setup(){
  pinMode(magnetPin, OUTPUT);
  pinMode(hallPin, INPUT);
  // Attach an interrupt to the ISR vector. DO I NEED THIS?
//  attachInterrupt(0, pin_ISR, RISING); //default interupt pin is always 0 on ATtiny85 (physical pin 7).
  timer = 0;                             //Reset the timer
}

void loop(){
  if(digitalRead(hallPin) && !hallMem){
    hallMem = true;               // One-shot memory.
    hallState++;
    delay(debouncing_time);       // Keep it simple.
    timer = 0;
  }
  if(!digitalRead(hallPin)){
    hallMem = false;              // Allow re-trigger.
  }
  if(hallState > 1) {
      digitalWrite(magnetPin, HIGH);        // Send 20 ms pulse to sensor activation coil.
      delay(20);
      digitalWrite(magnetPin, LOW);
      hallState = 0;                        // Reset the trigger.
  }
  if(timer >= 30000) {                      // No activity.
    system_sleep();
  }
}

// From http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void system_sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(INT0);                     // Use INT0 (PB2) as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
//  PCMSK &= ~_BV(INT0);                  // Turn off INT0 (PB2) as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts

  timer = 0;          // Reset the sleep timer on wake-up.
}

ISR(PCINT0_vect) {
}

Can anyone spot my error that is preventing a wake-up?
What is the ADC enabling instruction doing? Do I need it?
Many thanks.

Try to replace the PCMSK |= _BV(INT0);  with PCMSK |= _BV(PCINT2);

@gbg, that seems to be doing something, thanks. I'm going to add in an "awakeLED" so I can monitor the sleep status. It's bedtime in Ireland.

I believe your problem lies here:
PCMSK |= _BV(INT0);  // Use INT0 (PB2) as interrupt pin

You seem to have mixed up two sorts of interrupts:

INT0 (External Interrupt), which only works on pin INT0 (i.e. PB2)
and can sense low-level, rising edge, falling edge, or any change.

PCINT0 (Pin Change Interrupt), which works on any IO pin, but can
only sense “any change”.

Since you are sleeping in PWR_DOWN mode, pin change interrupt is the
appropriate choice. All your program is consistent with this choice but
for the line above.
The INT0 macro has the value 6. It represents bit 6 of GIMSK, which
is used to enable the INT0 interrupt. Not what you want. Bit 6 of
PCMSK is reserved, so you are not supposed to touch it. If you want
the pin change interrupt to sense changes in pin PB2 (aka PCINT2), you
instead have to:
PCMSK |= _BV(PCINT2);  // sense changes in PCINT2 = PB2

Thanks for the clear explanation. It works now. Can I leave out the ADCSRA lines as I'm not using any analog functions?

@Transistor: Indeed you can.


text:
SIM800L Arduino Pro Mini
I am trying to send an SMS using the Sim800L module and it seems to be unable to connect to the network. When I send the AT+COPS=? command it shows me a list of all the available networks along with the carrier of the sim card inserted but the module is unable to connect to the network. AT+CPIN returns an error as well. I read that changing the antenna will help but I don't think this can be the case as the networks are being detected. What could be going wrong?

what command you use to connect network? what error you get? what is the error with cpin command?

Are you giving it enough power?

Yes I am, the AT commands are working and it shows me available networks as well. Actually now when I looked at the available network and the signal strength, the carrier of the sim card installed is not appearing. Only two other networks, does this mean the module is not compatible with the network of the sim installed? Can it be that the sim card is 3G?

Make sure that you are giving it enough power, seaching and registering to a network needs a current peak of 2amps, if the model you are using has a built-in regulator plug it to a stable 5v 2amp source of power and try AT+COPS? again, it should work; you can try with the computer power supply it has a 5v 2amp source.