Transmit data between PC/Android phone and MCU

Go To Last Post
52 posts / 0 new

Pages

Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello.
I'm working on a device that receives a command, measures something and returns the results. (MCU: Atmega32)
I used a 3x4 matrix keypad and a 16x2 LCD to enter command and show the results but it made some problems:
1- The device is larger than what I expected. 
2- I had to use many jumpers (0 ohm resistors) to connect things on PCB. (One side wiring)
3- It's a little hard to type with keypad and show full result on a 16x2 lcd.
4- The program is larger than I expected and...

Now, I want to do this: connect atmega to PC/Android phone, send command to MCU, perform measurements, receive results on PC/Phone and show them.

My questions are:

1- Which method is better to transmit data? I'm a beginner and I don't know much about USART, 1Wire and... . Do I need any extra chips? (USB to serial and...) It's better to use less pins on MCU because I need them.

2- I don't know android programming or making software for windows. I just know a little C, C++ and web-based languages! What should I do ? Should I learn android/windows programming or there is an easier way? (I prefer  windows PC rather than linux PC or android phone.)

I use Atmel Studio 7 IDE and Atmega32 chip.

This topic has a solution.
Last Edited: Thu. Jul 11, 2019 - 11:56 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The usual way to connect a micro like AVR to an Android phone would be bluetooth. You can buy BT modules for micros that present a "UART" interface to the micro.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Buy a wifi or LAN module and connect it to your network? Then you could implement a webserver on your microcontroller and make your data input and output via a browser! This way it wouldn't matter if you try to connect from a Windows or Linux PC or Android or iOS phone or tablet.

- Brian

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Something like a BBC Micro:Bit or ESP32 might do what you want.

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The usual way to connect a micro like AVR to an Android phone would be bluetooth. You can buy BT modules for micros that present a "UART" interface to the micro.

An example is the RN4020 device...there are many others 

When in the dark remember-the future looks brighter than ever.   I look forward to being able to predict the future!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
I just know a little C, C++ and web-based languages!
JavaScript?

WebUSB in Chrome 61 and subsequent.

Building a Device for WebUSB  |  Web Fundamentals  |  Google Developers

by Reilly Grant

Reilly is a Software Engineer on Google Chrome focusing on hardware APIs.

...

Last updated May 29, 2019.

 

P.S.

pajuhesh80 wrote:
(MCU: Atmega32)
mega32U4 for a WebUSB demonstration.

Arduino goes via USB CDC so "might" be able to attach a USB UART to the mega32 though attaching a USB megaAVR would be more flexible as WebUSB has custom devices; USB PIC have some advantages over a USB megaAVR.

WebUSB may have USB HID; there are USB HID UART and the OS interfaces are relatively simple.

https://github.com/webusb/arduino#compatible-hardware

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Geronimo wrote:
Then you could implement a webserver on your microcontroller ...
or a WebSocket server.

There would be one very short web page on the MCU (a description of the operator interface of display data and virtual keys)

A WebSocket server and the HTTP data would squeeze into a mega32; would be easier to put the WebSocket server on an ESP8266, ESP32, or the WLAN module itself (some have a SDK)

Geronimo wrote:
... and make your data input and output via a browser!
via a Single Page Application (SPA) in JavaScript on the web browser.

Embedded WebSocket Server - Real Time Logic

(1/4 page)

The Minnow Server is specifically designed to facilitate the use of modern Single Page Applications (SPA) for device management and can be used with modern frameworks such as AngularJS, ReactJS, and Vue.js. See the video below for details.

[edit : video is mid-page]

...

 


About HTML5 WebSocket - Powered by Kaazing

Home - xPico 200 Series SDK (Lantronix®)

A Lantronix gateway has a "transparent UART"; iow, it's a terminal server with Ethernet and/or Wi-Fi to the LAN.

xPico 200 Series | Lantronix

Microchip Technology · GitHub (browse on AVR and/or WINC1500)

 

edit2 : or WINC1510

 

edit3 :

MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and Pycom modules) | MicroWebSrv

 

"Dare to be naïve." - Buckminster Fuller

Last Edited: Fri. Jul 5, 2019 - 05:32 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I had forgotten about a weird Arduino board called

the Yun, but this thread triggered a memory. You

can control the board by sending it http requests

like:

 

http [colon] //arduino.local/arduino/digital/13/1

 

and this causes digital pin 13 to be set. I thought it

was just a curiosity, since it's an incredibly inefficient

way to control an MCU, but if you have a spare $60

it might be something to consider.

 

--Mike

 

EDIT: made the http link not look like a real link

 

Last Edited: Fri. Jul 5, 2019 - 05:10 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

For the simpest interface to a mobile device you really have two choices - bluetooth or WiFi. Having done both, WiFi is probably the easiest solution. Bluetooth usually needs an app to be written for the mobile device, although there is Web Bluetooth that might makes things easier. For the likes of the BBC Microbit, there may already be pre-written apps that allow you to have buttons, sliders etc. I mention the Microbit (sorry Microchip!) as it is targetted to school children and there is a large amount of support. You can use Arduino for it as well - there's a number of choices for this platform.

 

Something that I'm using at the moment is the ESP32. (again,sorry Microchip). There is a framework called Mongoose OS that brings together WiFi with a webserver, websocket, bluetooth and just about everything else you'd want with an online compiler. It serves up a webpage and has a variety of means to communicate from the webpage down to the port pins - be it via websocket using your own protocol or using their REST protocol. You can do most of the work in a chopped down javascript on the ESP32 without touching a line of C. It has drivers for most of the usual suspects. You can get boards for around USD $15 for the official ones or cheaper for 'others'. Mongoose OS will work on Microchip product, but there hasn't been much call for it, so you'd have to go it alone.

 

 

As pennance to Microchip to touting other manufacturer's products, my current design has 3 out of 8 chips in total by Microchip. I needed to measure a number of 12V analog signals, so I used the PAC1934 - it takes up to 4 32V inputs and converts to 16 bit values. No need to play around with external resistor dividers - you get readings with millivolt resolution with better than 1% accuracy. This meant it didn't need to play around with multiplexers and level translation - I'm lazy. As well, it has high-side current sensing, so just add a sense resistor, and you measure bipolar current. Great for battery chargers. I had some channels left over, so I connected them up to the logic power. My board supplies 12V to external devices so I can measure the current drawn. The chip does all the scanning for you at up to 1024 samples per second, does averaging and calculates power as well! All via i2c, so the interface is simple. 3V3 or 5V logic. The chip is not super expensive either - I think around  USD $1.50 from Digikey in small quantities. I compared this with a TI part INA226 which is only single channel so Microchip stacks up much better. But I digress.....

 

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

One difference between BT and WiFi I guess is that BT is a local link whereas WiFi is very likely going to need device and controlling phone to both be in range of a router. Or is the suggestion that the phone itself acts as hot-spot and the device makes a local link?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

OK! Thanks for comments; But I forgot to say somethings:

I want it to be as cheap as possible!

I prefer to use cable (USB or AUX) instead of using wireless (BT or wifi) communication!

I don't want to use Arduino or anything like that; Just Atmega32 or Atmega644 on a main board with some other elements!

And I don't want my code to be large; I need to save MCU memory for main program; It is going to be very large and complex!

I want to do this: send a number,id or anything else to the MCU, perform the test and return result numbers.

I totally want it to be cheap, easy to use and simple!

Note: As I said, I'm really a beginner and I just know how to read and set pins, use timers, ADC, LCD and some C syntax and functions! blushlaughMy biggest project with 2 of my friends was a 16-sensor pathfinder robot that used Atmega32 (or 16), L298 motor driver, LM324n and... . I designed its PBC, wrote its code and helped in building, soldering and testing it! So please write comments as beginner can understand it easily! Thanks!

Last Edited: Sat. Jul 6, 2019 - 12:33 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You've got a few requirements there - how do you propose to talk to the android phone?

 

If it can be done, someone will have done it before - have you Googled?

 

I don't want to use Arduino or anything like that; Just Atmega32 or Atmega644 on a main board with some other elements!

 

 Arduino tools work with either of those devices.

I totally want it to be cheap, easy to use and simple!

Sure - but what if it cannot be done within your criteria? What is your plan B? 

 

[edit] I re-read your first post. ok, so a PC is acceptable. This is something that has been done to death with Arduino. Get yourself a usb->ttl serial board or a clone Arduino board as these are probably cheaper.

 

Last Edited: Sat. Jul 6, 2019 - 12:42 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Kartman wrote:
Get yourself a usb->ttl serial board

I agree.

By far the simplest thing is to forget the android phone for now and use a PC.

Look for 'USB to TTL serial adapter'.

This appears to the PC as a serial port (COM port in windows terminology).

You can use any number of terminal programs on the PC to send/receive data over this 'virtual' serial port.

At the microcontroller end, you conect to the UART tx/rx pins.

There is plenty of information available about using UART on microcontroller.

 

At a later stage, you could then replace this UART connection with a Bluetooth serial port module to connect to an android phone over BT.

The code on the microcontroler would be the same, but at this point you would probably have to write a program to run on the android phone (never done it so don't know how much hassle that would be, but there must be lots of examples where other people have already done this).

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Well, I guessed that using PC is easier than android phone. I have an Arduino UNO clone, but when its possible with Arduino, surely it is possible with standalone Atmega also!

I want my device to be fully functional standalone. Like STK500 programmer that I use (made by Noavaran Electronic co); I connect it to my laptop using USB. As I understood, it uses a USB to Serial chip.

Maybe I build many of my device and sell them to other people!

I used google a lot and I didn't find my answer.

Note: I even don't know how to transmit data between an Arduino and PC! I used my Arduino clone for a project that its code was written before by someone else and I just had to assemble its hardware. I don't know how to write code for Arduino.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
I have an Arduino UNO clone, but when its possible with Arduino, surely it is possible with standalone Atmega also!

Of course it is possible, the difference is, the UNO clone will already have a USB to TTL converter chip on the board.

So it makes life very easy.

I would start with the UNO clone and learn about using the UART (EDIT: and in case you're still wondering, this doesn't mean you have to use the Arduino programming environment, just view the UNO clone as an AVR ATMEGA328 chip that has been conveniently placed on a board along with the USB to TTL converter, voltage regulators etc. ready for you to use, and all at a very cheap price!).

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

As others have said an Arduino is little more than an AVR and a USB-UART converter. If you want to use just an AVR you'll need one of the $2 USB-TTL cables from ebay.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks! This is what I wanted. I can't buy from eBay (I'm in Iran); But I found these modules in local internet shops:

PL2303 USB to TTL

CH340 USB to serial

Which one is better for me? USB to TTL? It would be very good if I can use that USB module as main board power supply also.

It would be very good if I can put CH340G or PL2303HXA chip directly on my board and add a USB port to it!

I'll search for TTL connection and its code and I'll appreciate any help about this!wink

Another question: Are these modules just for PC to MCU or both PC to MCU and MCU to PC?

Note: My Arduino UNO clone ("Arduino" isn't printed on board, just "UNO") uses CH340 and ATMEGA328P chips. I think I should use CH340.

EDIT: I found that I can put both ICs on my board. I prefer to use CH340G. Just one question remaining: How should I send/receive data? Using Atmel studio Terminal Window? If yes, how should I use it? Just select COM,Baud,ASCII and press Connect?  For example, I want to send "HELLO" string and "512" integer to the MCU, and after that MCU send "BYE" string and "1024" integer to the PC and PC show it.

Last Edited: Sat. Jul 6, 2019 - 05:52 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The disadvantages of WebUSB :

  • not USB CDC ACM
  • only Chrome and Opera
  • Android device has to have USB Type-A, Type-AB, or Type-C

 

Inexpensive USB UART have the USB device descriptors hard-coded in HDL or stored in ROM; other USB UART store the USB device descriptors in internal or external EEPROM or flash.

A USB MCU can be in-lieu of a USB UART; if a mega32 is low on program space, data space, clocks, or I/O then functionality can be moved from the mega32 to the USB MCU.

Microsoft Edge is underway in the effort to change its engine to Chrome's; WebUSB might still be disabled in the new Edge.

 


Building a Device for WebUSB

by Reilly Grant

...

 

Platform-specific considerations

...

Android

https://developers.google.com/web/fundamentals/native-hardware/build-for-webusb/#android

 

...

Last updated May 29, 2019.

https://developer.mozilla.org/en-US/docs/Web/API/USB#Browser_compatibility

MCP2221A - USB - USB Bridge (64 bytes of flash so am uncertain it's a fit for WebUSB)

USB to UART Controller (Gen 2) - Cypress Semiconductor

Replacing FT232R with CY7C65213 USB-UART LP Bri... | Cypress Developer Community

USB to UART Archives | Prolific USA | IC Design & Manufacturing (OTP might fit WebUSB, EEPROM-capable appear to be only for USB CDC ACM)

edit :

NEW! USB to UART G Series Archives | Prolific USA | IC Design & Manufacturing (may be only USB CDC ACM though larger OTP ROM and pins for an external EEPROM)

edit 2 : PL2303G has an Android driver for all but PL2303GB so it might be WebUSB capable.

edit3 : PL2303 Android Driver Solution | Prolific Technology

 

"Dare to be naïve." - Buckminster Fuller

Last Edited: Sat. Jul 6, 2019 - 05:12 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Kartman wrote:
Bluetooth usually needs an app to be written for the mobile device, although there is Web Bluetooth that might makes things easier.
also MIT App Inventor if one doesn't want to go through Android Studio; Microsoft Visual Studio is an alternate IDE for Android application development.

Kartman wrote:
I mention the Microbit (sorry Microchip!) as it is targetted to school children ...
and computer science undergraduates (young adults, early young adults)

 


About Us | Explore MIT App Inventor

via Quick Links | Martyn Currey (also : top bar, 'Bluetooth Control Panel' for a Bluetooth 2 app on Android)

Ada on the micro:bit - The AdaCore Blog

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

clawson wrote:
... is that BT is a local link ...
or a mesh network that's optional in Bluetooth 5; contexts are building control and multi-room in a house.

Qualified Mesh Products | Bluetooth Technology Website

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for comments but please stop commenting about BT/wifi! I don't want to use android phone anymore! Just please answer my questions about serial communication! Thanks again!

EDIT: I think I can use android phone if I can use USB to serial. Apps like "Serial USB Terminal" may help.

Last Edited: Sat. Jul 6, 2019 - 06:22 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
Like STK500 programmer that I use (made by Noavaran Electronic co); I connect it to my laptop using USB.
fyi and IIRC, STK500v2 was recently added to ZFlasher AVR (Android)

Note, Android's USB is a subset of the USB in Windows, macOS, Linux, and BSD.

pajuhesh80 wrote:
Note: I even don't know how to transmit data between an Arduino and PC!
If Windows 10 then communication with Arduino was simplified.

USB CDC and Arduino is also available in Windows 8.1 and earlier though there's a few more short hurdles to jump.

USB HID is simpler than USB CDC though its speed is an order of magnitude less than USB CDC.

 


ZFlasher AVR - Apps on Google Play (an Android port of AVRDUDE over USB host OTG)

...

 

USBasp

AVRISP mkII

USBtiny

STK500v2

AVR109

Arduino bootloader

 

...

 

What's new

Support serial programmers and Arduino bootloader
avrdude update to latest version from SVN
Chip erase option add 
Support the advanced fuse edit is extend

 

...

 

1.5

Apr 10, 2019

...

Arduino bootloader goes via USB CDC; am guessing it's custom USB device descriptors within ZFlasher AVR.

If you don't have access to Google Play then browse F-Droid for AVRISP apps (maybe a large subset of Android apps are already accessible via F-Droid)

/r/Android App store | F-Droid - Free and Open Source Android App Repository via https://prism-break.org/en/all/#app-store

 

What is new with Serial in Windows 10 - Microsoft Tech Community - 270855

First published on MSDN on Jul 29, 2015

Authored by George Roussos [Microsoft]

...

 

Now devices that report these compatible IDs:

[USB CDC]

… including popular prototyping boards like Arduinos – just work with our built-in driver. 
 

...

 

Windows 10 SDK includes two Universal SDK samples illustrating this API:

...

    1. New SerialArduino SDK Sample from above //build talk is now available including C# and Arduino sketch source code.

 

...

 

C code for Teensy: USB Raw HID - for building custom USB devices

 

edit : typo

 

"Dare to be naïve." - Buckminster Fuller

Last Edited: Sat. Jul 6, 2019 - 07:30 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
PL2303 USB to TTL

CH340 USB to serial

Which one is better for me?

Opinion : PL2303 though CH340 appear to be more popular on Arduino clones; either for dwire-debug.

The follow-on to PL2303(E,H,R,S,T) is PL2303G (crystal-less, Android) though I was unsuccessful in locating a supply source of PL2303G (may your search results be greater than mine)

pajuhesh80 wrote:
Another question: Are these modules just for PC to MCU or both PC to MCU and MCU to PC?
both

 


debugWIRE via USB UART | AVR Freaks

NEW! USB to UART G Series Archives | Prolific USA | IC Design & Manufacturing

 

edit : Android

 

"Dare to be naïve." - Buckminster Fuller

Last Edited: Sat. Jul 6, 2019 - 07:27 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
Just one question remaining: How should I send/receive data? Using Atmel studio Terminal Window? If yes, how should I use it? Just select COM,Baud,ASCII and press Connect?  For example, I want to send "HELLO" string and "512" integer to the MCU, and after that MCU send "BYE" string and "1024" integer to the PC and PC show it.

To send text like "hello" and integers like 512,  the best way is to send everything as text (have a look on wikipedia for ascii table).

In other words, send 512 as the character string "512".

The microcontroller can easily convert from the character string "512" to the number 512, and convert the number 1024 to the  character string "1024".

You will be able to find plenty of tutorials and examples, this is all very common stuff.

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
EDIT: I think I can use android phone if I can use USB to serial.
if the Android phone has USB Type-A, Type-AB, or Type-C; some Android devices have USB OTG so then good to go.

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

MrKendo wrote:
...  the best way is to send everything as text ...
Standard I/O and/or formatted I/O is not necessary for minimally essential function MCU applications as the conversion can be done in an OS (Android, iOS, Windows, macOS, Linux, BSD, etc) unless the message data is required to be in ASCII or Unicode.

avr-libc: <stdio.h>: Standard IO facilities

(second paragraph)

Due to space constraints, some functionality has not been implemented at all (like some of the printf conversions that have been left out). Nevertheless, potential users of this implementation should be warned: the printf and scanf families of functions, although usually associated with presumably simple things like the famous "Hello, world!" program, are actually fairly complex which causes their inclusion to eat up a fair amount of code space. Also, they are not fast due to the nature of interpreting the format string at run-time. Whenever possible, resorting to the (sometimes non-standard) predetermined conversion facilities that are offered by avr-libc will usually cost much less in terms of speed and code size.

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

gchapman wrote:

Standard I/O and/or formatted I/O is not necessary for minimally essential function MCU applications as the conversion can be done in an OS

True, but life is much easier as text, assuming you want MCU to return messages like "Result = 12345" where 12345 is the value of some variable at this point in time, and to be able to view those messages in a terminal.

It doesn't take much code for simple atoi and itoa functions (avr-libc provides such functions, or write your own).

The atoi probably wouldn't be needed anyway, more likey just the itoa.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

As I understood from your comments, I have to use printf function to send data from MCU to PC. Like print function in bascom-avr.And scanf to receive data from RX and TX. I'll test it on my UNO Clone.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There are zillions of examples of exactly what you want to do out there. You wanted simple, but methinks you're making it extremely hard for yourself!

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Until today, I put a 10 pin ISP port on my boards to be able to update their program without taking off the MCU. Now as I found, I can use serial port to program MCU. Just like my UNO Clone. I'll search more about it.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Not really! It's going to be better and easier than the code that I wrote for matrix keypad and 16x2 LCD! Also writing commands in terminal by PC keyboard on PC monitor is easier than writing it by a 3x4 keypad like old phones on a 16x2 char LCD for user! And I can show results better in terminal. Maybe I learn writing windows executable programs and make a GUI for it in future! :)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You've got a Arduino board - the simple solution is to use Arduino tools. As I said, zillions of others have done what you want to do. There's nothing magic about an Arduino - all they did was take a microcontroller, put it on a pcb with the bare minimum, add a bootloader and an interface to easily program it. Then the software tools bring together all the grimey bits and pieces so you don't need to worry about setting the clock or whatever so you can concentrate on what you want to do rather than get bogged down in the tricky bits. Write code, press button. Rinse and repeat. You talk about simple - they answered your question. You can do the same with your mega32 or 644. Arduino tools support them as well. But you need to do the tricky work of ensuring the hardware is correct. For someone with limited experience, that is the hard part.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I agree with you about Arduino. I know that It's not a magic thing! :)
And about experience, I'm beginner in Atmel studio; Till two months ago I used bascom. And one of my friends is even more experienced in hardware than me.
Don't worry! I know what am I doing! ;)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
Don't worry! I know what am I doing! ;)

 

Your quote normally precedes a major failure.

 

Again, you wanted simple - you've broken your rule.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:

As I understood from your comments, I have to use printf function to send data from MCU to PC. Like print function in bascom-avr.And scanf to receive data from RX and TX. I'll test it on my UNO Clone.

Not necessarily printf / scanf.

These functions, because they are general purpose and can do almost anything, will use up a lot of code space.

There are simpler functions like itoa / utoa if you don't need the full general purpose capabilities of printf (and you almost certainly won't need the full general purpose capabilities).

Either way, whichever functions you use, you will need first to implement an underlying 'send a character out the UART' function, and likewise for receive.

Arduino environment already includes interrupt driven uart rx/tx with circular buffers.

You will need to implement something similar (maybe copy the Arduino code).

Or at least consider getting your project working first in Arduino environment, where you can simply say serial.print(stuff) and it just works.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Again: putting a ch340 chip on board, connecting it to usb and atmega and writing a few lines of code is much easier and much more simple than connecting a 16x2 LCD and a 3x4 keypad to MCU and write more than 200 lines of code for it! Also, for user, it's easier to connect device to PC and write commands and receive results in terminal than entering command with a keypad and read results on LCD. Please just answer my questions; I exactly know what am I doing! :)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

So I shouldn't use printf and scanf functions. Could you please tell me which functions should I use? I'm planning to do things on my UNO Clone first (after some simulations); Because it also uses CH340 USB to Serial chip; And I can' build the main device right now.
Note: I want to code in Atmel studio environment. So please tell me the functions that they are for avr gcc compiler.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

It's not as simple as 'tell me which functions to use'.

You will have to take it step by step.

First thing is to be able to setup the UART hardware, and send and receive a single character.

You have to write these functions.

Once you can send/receive single charcaters you can build on this.

You also have to decide whether to use interrupt driven tx/rx, or non interrupt 'blocking' functions.

For tx, since your MCU knows when it wants to tx, the non interrupt 'blocking' approach can be fine.

For rx, since your MCU doesn't know when it will receive a character, it's not so simple. Non interrupt 'blocking' approach might be OK, but it is common to use interrupt driven rx with a circular buffer.

So already, there is a lot to get working before you even worry about which function to use to convert a value like 12345 into string "12345", or which functions to use to process an incoming message like "rf" (read_foo) or "wf 123" (write_foo 123).

But this has all been done millions of times before, I'm not going to repeat it here, there are numerous tutorials and examples.

 

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

OK. Im searching about it. And something else: I already know "which function to use to convert a value like 12345 into string "12345" ", it is itoa. laugh

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Note: Arduino uses avr-gcc. You can use the Arduino libraries in Atmel Studio. How simple do you want it?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

How can I do this? It would be very good.
But, good news:
I found how to send and receive byes using UART and wrote some functions to send and receive strings, also! This page helped me:
https://www.kanda.com/AVR-C-Code-UART.php
Also, I did the same with arduino before coding in Atmel studio. Everything is OK in proteus 8 simulation. I can't test on a real circuit now, but I'll post results as soon as I made and tested the real circuit.
I'll post my code soon.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
How can I do this? It would be very good.
Well the simple method is simply to write a sketch in Arduino that uses the libraries you are interested in. Then use the AS7 feature to "create project from Arduino sketch" and it will pull everything in that is required. This does, however, raise the question of "why not just do it in Arudino IDE anyway - what advantage does AS7 bring?"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I just wanted to know how to do that!

A new question: Before, I connected MCU to stk500 using an ISP connector; Now I want to be able to program MCU using RXD and TXD pins to make MCU firmware (program) update easier and also remove ISP connector from my board.  I found "MightyCore" but I didn't understand something: After burning bootloader, am I able to upload my main program using Atmel Studio (using USB to serial (UART)) or I have to do this using Arduino IDE? I can't use Arduino IDE as my main IDE!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is a sample of my code (main code is better):

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#define USART_BAUDRATE 38400   
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

volatile unsigned char value;
void USART_Init(void)
{
    UBRRL = BAUD_PRESCALE;
    UBRRH = (BAUD_PRESCALE >> 8); 
    UCSRB = ((1<<TXEN)|(1<<RXEN));
}


void USART_SendByte(uint8_t u8Data)
{
  while((UCSRA &(1<<UDRE)) == 0);
  UDR = u8Data;
}

uint8_t USART_ReceiveByte(){
  while((UCSRA &(1<<RXC)) == 0);
  return UDR;
}

void Led_init(void){
    DDRB =0xFF;       
    PORTB = 0xFF;        
}

int main(void){
   USART_Init();
   sei();
   Led_init();
   value = 'A';   
   PORTB = ~value;
   int i;
   char String[100];
   int STRsize;
   
   while(1){
             
     while((UCSRA &(1<<RXC)) == 0);
	 
	 for (i=0;i<100;i++)
	 {
		 String[i] = '\0';
	 }
	 
	 for(i=0;;i++)
	 {
		 String[i] = USART_ReceiveByte();
		 USART_SendByte(String[i]);
		 if (String[i] == 13)
		 {
			 break;
		 }
	 }
	 
	 if (strcmp(String,"Not") == 13)
	 {
		 USART_SendByte(33);
	 }
	 
	 STRsize = strlen(String);
	 
	 for (i=0;i<STRsize;i++)
     {
		 USART_SendByte(String[i]);
     } 
   }
}

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
	 for (i=0;i<100;i++)
	 {
		 String[i] = '\0';
	 }

This is why God invented memset() ;-)

	 for(i=0;;i++)
	 {
		 String[i] = USART_ReceiveByte();
		 USART_SendByte(String[i]);
		 if (String[i] == 13)
		 {
			 break;
		 }
	 }

There is no protection here for i exceeding the [100] size of String ?

	 if (strcmp(String,"Not") == 13)

That is a VERY odd use of strcmp. Exactly what are you trying to check here?

		 USART_SendByte(33);

I had to look it up (as will most readers) so the actual intention here is presumably?:

		 USART_SendByte('!');

The code is more readable if you don't rely on the reader knowing the canonical order of the ASCII character table!

 

PS Oh and...

   sei();

Nothing in the code uses interrupts - you should be very careful about enabling interrupts when you don't have to - if you had inadvertently set some IE bit then this would have been the final nail in the coffin.

   value = 'A';
   PORTB = ~value;

A couple of things - as you do not use interrupts there is no reason why "value" needs to be volatile but anyway this is a very curious piece of code. Now I already know that the binary pattern for 'A' is 0x41 or 01000001 therefore ~'A' is 10111110 so why have you chosen that specific bit pattern to write to port B? It is very odd to write ASCII to port pins !

 

Oh and that code immediately undoes what Led_Init() just set PORTB to.

Last Edited: Wed. Jul 10, 2019 - 09:22 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you're trying to capture a complete 'line' (with end of line indicated by either a CR or LF or both) into a buffer, and then process that complete line, I would sugest a pattern something like

static void process_line(uint8_t *buf)
{
    /* buf contains a null terminated string, do what you want with it,
     * as an example just transmitting the whole string back */
    while (*buf != '\0')
    {
        USART_SendByte(*buf++);
    }
}

#define BUF_SIZE 100

int main(void)
{
    /* +1 so always room to null terminate */
    uint8_t buf[BUF_SIZE + 1];
    uint8_t write_index = 0;

    /* stuff */

    while (1)
    {
        uint8_t c = USART_ReceiveByte();

        /* end of line if receive either a CR or LF */
        if (c == '\r' || c == '\n')
        {
            /* ignore CR or LF if buf empty */
            if (write_index != 0)
            {
                /* so buf can be treated as null terminated string */
                buf[write_index] = '\0';
                process_line(buf);
                write_index = 0;
            }
        }
        else if (write_index < BUF_SIZE)
        {
            buf[write_index++] = c;
        }
    }

 

This reply has been marked as the solution. 
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Oh! I forgot to clear that sei()!

As I said, this is a sample and main code is better. It was just for testing.

About sending character '!' instead of 33 you are right.

I didn't know what is memtest()! I'll search about it.

This "if (strcmp(String,"Not") == 13)" was because of that I pressed enter to sent command and the string was actually like "Not\n" and pressing enter caused that 13;

Again: Everything was just for testing! ;)

Here are some of functions in my main program:

void USART_Init(void)
{
	UBRRL = BAUD_PRESCALE;
	UBRRH = (BAUD_PRESCALE >> 8);
	UCSRB = ((1<<TXEN)|(1<<RXEN));
}
/***********************************************/
/***********************************************/
void USART_SendByte(uint8_t u8Data)
{
	while((UCSRA &(1<<UDRE)) == 0);
	UDR = u8Data;
}
/***********************************************/
/***********************************************/
uint8_t USART_ReceiveByte(void)
{
	while((UCSRA &(1<<RXC)) == 0);
	return UDR;
}
/***********************************************/
/***********************************************/
void USART_SendString(char *String)
{
	int i;
	uint8_t STRsize = strlen(String);
	
	for (i=0;i<STRsize;i++)
	{
		USART_SendByte(String[i]);
	}
}
/***********************************************/
/***********************************************/

My loop(edited):

while (1) 
    {
	    USART_SendByte(13);
	    USART_SendString("Enter String:");
	    USART_SendByte(13);
	    
		
		for (i=0;i<16;i++)
		{
			String[i] = '\0';
		}
		
		for(i=0;i<16;i++)
		{
			while((UCSRA &(1<<RXC)) == 0);
			
			String[i] = USART_ReceiveByte();
			
			if (String[i] != 8)
			{
				USART_SendByte(String[i]);
			}
			
			if (String[i] == 8 && i > 0)
			{
				USART_SendByte(String[i]);
				String[i] = '\0';
				i--;
				String[i] = '\0';
				i--;
			}
			else if (String[i] == 8 && i == 0)
			{
				String[i] = '\0';
				i--;
			}
			
			if (String[i] == 13)
			{
				String[i] = '\0';
				break;
			}
		}
		
		check_String(String); //process string...
		
    }

What can I use instead of 13 and 8 for Enter and Backspace?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:

Thanks! This is what I wanted. I can't buy from eBay (I'm in Iran); But I found these modules in local internet shops:

PL2303 USB to TTL

CH340 USB to serial

Which one is better for me? USB to TTL? It would be very good if I can use that USB module as main board power supply also.

 

Can you buy from Aliexpress? Other good choices are CP2102 from Silicon Labs and HT42B534 from Holtek. Avoid FTDI, there were some incidents in the past with fake chips and overzealous IP enforcing.

 

If you want to design an actual product that will be commercialized and need to worry about sanctions, well Silicon Labs is US based, so... avoid. There are also AVR clones from a Chinese company, previously discussed in the forum: https://www.avrfreaks.net/forum/...

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for your advice!

My UNO clone is Chinese already! Original is very expensive!

Also I didn't find both HT42B534 and CP2102 in local internet shops.

I can't buy from Aliexpress, Also.

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

CH340 is popular with the Chinese clones. It doesn't seem to work too well at the very high baud rates like the cp2102, but 115200 seems to be ok.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

pajuhesh80 wrote:
This "if (strcmp(String,"Not") == 13)" was because of that I pressed enter to sent command and the string was actually like "Not\n" and pressing enter caused that 13;
It's not doing the test you think. strcmp() basically has one usable result and that is whether the return is 0 or non 0. If it is 0 it means it reached the end of the string and everything compared the same so far. If it returns anything else it's simply reporting the first place where there was a difference.

 

If the plan was really just to test if the string contained "Not" then I would suggest testing strstr(String, "Not") and checking for a non-0 return is a better test (though this will work wherever "Not" appears in the string. Perhaps strncmp() would have been better. You can tell that to "just check 3 characters" to see if the first 3 are "Not".

 

I'd suggest that learning about things like strcpy(), strncpy(), strstr(), etc etc is possibly easier done when programming a PC where the debuggers are better and the results are more immediate (printf() just works!)

Pages