NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » python loop

August 02, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

I have the ledarray up and running,i found some code and it work's but i can't make it loop. I've tryed every combination from what i know of the code, got past the syntax error but now it says: Name error: name 'while_do_scroll' is not defined. I'm with kubuntu now and i think my problems might be with the editor, it's talking non ascii and encoding "utf-8". Linux mumbojumbo, too tired of linux to spend more time trying to figure it out.So add a loop that works please. Also would like to send a live feed to it. I'm right there i just can't see it. I got an address just don't see where to put it. Any tips would be good.

#!/usr/bin/python
import serial
import sys

serial = serial.Serial("/dev/ttyUSB0", 115200)
mystring = sys.stdin.readline()
scrollMode = True
lastTime = ''
serial.write('b')
for data in mystring:
    if not data == '\n':
                serial.write(data)
                response = serial.read()
                if not response == 'n':
                        print "Received: " + response
                        #This is a debug line, since I'm a bit fuzzy on some details
                        break
while_do_scroll
August 03, 2009
by jbremnant
jbremnant's Avatar

Looks like you are just reading the input from stdin (your keystrokes from the terminal) and sending each character via serial line to nerdkit unless it's a newline ('n'). And it breaks out of the loop if the nerdkit code doesn't respond with 'n' character.

Couple of things I would change:

  • while_do_scroll is not an existing named loop. You might want to delete it.
  • you only read from stdin once. So the top loop you have is only designed to loop through your input characters once.
  • if your nerdkit code is not responding back with 'n' character, you want want to take out the "break" statement so that you don't exit out of the loop prematurely.

Here is the code change I would make:

#!/usr/bin/python
import serial
import sys

serial = serial.Serial("/dev/ttyUSB0", 115200)
scrollMode = True
lastTime = ''
serial.write('b')

while True:
  mystring = sys.stdin.readline()  # read indefinitely
  for data in mystring:
    if not data == '\n':
      serial.write(data)
      response = serial.read()
      if not response == 'n':
        print "Received: " + response
        # break

Hope that helps.

August 03, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Okay, i've just loaded your changes and it's, Received: b Received: a

That's it nothing showing up. Before it would scroll once.

August 03, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

UPDATE got it working but still no loop. Seems to me there should be a "while" or "for" there. Also you left the #break in. I took it out but still no loop.

August 03, 2009
by mcai8sh4
mcai8sh4's Avatar

Farmerjoecolege : I'm useless at python, but it looks like you're using the code (or similar) that I modified from the origional Nerdkits supplied code. The basic behind this is quite simple, it takes arguments from the command line (when the program is invoked) and sends them to the display then ends.

If you're wanting to send a live feed to your display, then I recommend the original Nerdkits py-listener program. It constantly listens on a port so you can just send your data to that port and it will be displayed. This program was designed for use in a bash script (batch file, whatever you want) to be invoked when needed. That is, it just displays the one thing then ends, when you can run it again with your new data etc..

I have wrote 2 other programs (one displays static text for 5 sec, the other scrolls like this) in perl - these are for the same usage, but where intended for those who may have been struggling with python (mainly under Windows).

If you let me know exactly what you are trying to achieve, then I'll try to modify the program (probably the perl one - I don't know python, but I can always try) to help you achieve your goal.

One thing I've noticed - any of these programs don't always work first try - so run it once, then again, then again (leave the marquee on, eventually it listens at the right place - then it seems to work ok [this is a little bug I'm trying to iron out])

Best of luck, keep us all posted on how you get on.

(I'm quite busy at work so it may be a few days to get round to trying to help, but I'll do my best)

August 03, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Alright, good. So i'm beginning to think that the code i'm trying to modify will not "loop". That's all, like get the code running, add the text and instead of stopping, to loop. And a timing interval would be good too. Sorry just don't know how to code yet.

August 03, 2009
by mcai8sh4
mcai8sh4's Avatar

You want to loop the same data? This is probably within my capability (if thats what you're after),

If you're after it to read new lines constantly, then you're better off with the py-listener.py program

August 03, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

I'm sitting here staring at the py listener and the only thing going across it is what i enter from the key board. If i enter a address for a live feed it'll scroll just that. Where's the loop and connection to the feed?

August 04, 2009
by jbremnant
jbremnant's Avatar

The program I supplied you doesn't do anything except display what you type on the keyboard. In order to get live feed to scroll on your nerdkit, you'd first need have a client that can download messages from the feed and send the contents to the nerdkit. Again, just like mcai8sh4 mentioned, use the original py-listener.py script. Once you get that working, you will need "netcat" program to send messages to py-listener.py script, which in turn will communicate with your nerdkit. After that, you can do something like this to test on your linux command line:

echo "SOME INFO" | netcat localhost 6667

I strongly suggest going through the original code and try to understand it line-by-line. And modify the code as necessary.

August 04, 2009
by mcai8sh4
mcai8sh4's Avatar

I think like jbremnant suggested - you need a client (of some sort) to pull the info off the web - once you have the information accessible you could then use either the origional py-listener, or one of the other adaptations.

It would certainly be beneficial for you to understand how the python (and c code) intereact with each other, then you will know what needs to be done to display your live feed information.

I know the c code is quite confusing - believe me, I don't fully understand it yet - but the basic read a character, once ready for the next, send an 'n' and wait for the next... should make sense. It's usually best to break down each part of the code and figure out what it's doing (in general), then piece all that together to understand the basics of the code.

Once you're comfortable with how you are sending/receiving the data (try not to worry about how it's actually displayed) then you can start to work on a client (even something simple like a bash script) to grab the data you want and send it to one of the python programs.

Good luck

August 04, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Ok, i'm working on a rss client right now. Just got to figure out the rest. Bash scripts are almost python scripts, so i'll stick with the python. Also, I don't know how you guys get, echo "SOMETHING" | netcat localhost 6667, to work. With me with py-listener running, in the second window it's: nc localhost 6667 and then it's ready. So netcat is refusing the connection right now for some reason. And i still don't know how to add a simple loop to the scrolling script.

August 06, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

So now let me rephrase the question. I need someone to write me some code (just send price). All it's got to do is take a string of text, scroll it and loop it every 5 sec until new text received. Easy eh! Don't care what language, just a command line script.

August 08, 2009
by wayward
wayward's Avatar

Farmerjoecoledge,

I don't think I fully understand what kind of scrolling you had in mind, so I wrote two functions. One will split your input line into individual characters and output them, the other will echo the line successively, stripping characters from the front until the entire line is cannibalized. If you write such a line to the LCD, it will appear to be scrolling to the left. (Don't forget to add one trailing blank character to erase what's left of the old, one-character-longer line!)

Oh, and this is a bash script. It relies on sed to do the heavy lifting. You can modify the main loop (at the end) to adjust the pause (sleep 5, in seconds) or what happens when the line is output. Then pipe the output of the entire script to the serial port, loop on the MPU side waiting for a newline-delimited string, do whatever you like, and you're done.

Cheers, Zoran

#!/bin/bash

# set input field separator to null char to preserve leading spaces
# when using the read builtin
IFS=$'\0'

# split $line into newline-separated characters
function echo_chars()
{
    sed 's/./&\n/g' <<< $*
}

# trim first character and print, repeating until depleted
function deplete_line()
{
    sed ':loop; p; s/.//; t loop' <<< $*
}

# read a line to process
read line

# apply desired function to the line
deplete_line $line | while read l; do
    echo $l
    sleep 5
done
August 08, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Zoran, Ok, this is good. One thing, this is the ledarray that i want this to work on. But just to see if i'm on the right track, i'm new to bash. So i used sed as the command to run the script.Seems to work it waits for text to be sent.

Grant

August 09, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

I've reconnected the lcd, entered bash bash (i named the code bash) and it's ready for text so i enter THANX and it cannibalizes one letter at a time like it should but nothing shows on the lcd. What am i missing? And i don't know what is meant by sed doing the heavy lifting. Should there be a sed shell open?

August 09, 2009
by wayward
wayward's Avatar

Hey Grant,

this program cannibalizes letters and outputs the text on what's called "standard output". It's just a "channel" for the textual output from a program; by default it's connected to your terminal so you can see it on screen. But you can also redirect standard output (or stdout as we call it) to a file, to a different terminal, or use it as input to an entirely different program, just as if you were typing on the keyboard! This kind of redirection from one program to another is very common practice in most UNIX-based operating systems, and it is tremendously useful, as you'll see.

In our case, I wrote a program that sends some text to stdout. You want to redirect that text to your LCD. You have several options, but the easiest one is this:

- get py-listener running
- bash bash | nc localhost 6667    # note the '|' character -- it does the redirection
- now enter the text to scroll

The '|' character means this: "take whatever the program on the left-hand side would write to the terminal (its stdout) and redirect it to the keyboard input of the program on the right-hand side (its stdin, yes, standard input)". Note that exactly the same thing happens when you write

echo "some text" | nc localhost 6667

That's redirection at work.

Try it out and let me know; I am curious myself :)

Zoran

August 09, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Zoran, are you curious? So you don't know? Ok your on the right track. So the redirect is where i'm still lost. The bash script is one program, python-listener.py is another and nc (netcat) is another. We seem to have lost sed that would be four programs working together. The combinations do not work. I'm not getting the text on screen. With the python-listener.py it's written to work with nc, meaning after py-listener is running you open a second shell to open port 6667. That command is not, echo HOWRU | nc localhost 6667 to open the port it's nc localhost 6667 by itself. The shell changes to a nc shell and then it's ready for text. I read echo SOMETEXT | netcat localhost 6666, right at the beginning of the ledarray tutorial and has still to make sence. With the spinoffs from the python-listener.py code(1st q above) the port opens (it seems) automaticly. Nc is not needed. So i realize the bash script needs a port open but nc isn't it, maybe it should be sed, i'll look into that. Now i'm not too concerned that it's not working for the lcd yet, It's my code for the ledarray is what i don't got. So forget about the lcd for now. I need some code to receive text scroll it and loop every 5sec's until new text received on the ledarray.

Grant

August 10, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Ok Ok already i know it's not easy but don't u guy's like a challenge. Just thread nc with the scroll program? I'm trying to get this code so making another ledarray will be worth it. My first one i used superbright leds and she don't work right. Then if i'm still alive i'll get serious about learning "A" language.

August 10, 2009
by wayward
wayward's Avatar

All right, we're getting somewhere. Now, as for netcat: if it can read some text from the keyboard (nc ... then type "blahblah"), then it can certainly accept it via pipes (echo blahblah | nc ...) . The two methods are identical.

sed is a standard UNIX utility for manipulating the sequential inputs, such as the text you want to scroll. I use it here to trim letters from the input string and print intermediate results, which will -- when we manage to show it on the marquee -- create an effect of scrolling. So, what sed does is simply manipulating strings; it doesn't talk to the MCU.

I tested the python-listener.py on my computer and it works fine with what I wrote above; what error are you getting? I'll write it here once more:

  • start python-listener.py
  • in another terminal: bash bash | nc localhost 6667
  • type your message and hit Enter

Also, I've modified the script to also accept the text from the command line; this version below will work with: bash bash HowDoYouDo | nc localhost 6667 so you don't have to enter the text by hand. This is just a minor cosmetic edit, though, so you're free to ignore it.

Please let me know what happens, if anything, when you try the above. I am curious because I don't actually have the LED marquee myself :)

Cheers, Zoran

#!/bin/bash

# set input field separator to null char to preserve leading spaces
# when using the read builtin
IFS=$'\0'

# split $line into newline-separated characters
function echo_chars()
{
    sed 's/./&\n/g' <<< $*
}

# trim first character and print, repeating until depleted
function deplete_line()
{
    sed ':loop; p; s/.//; t loop' <<< $*
}

# collect arguments as input, or read a line from stdin if none given
line=$*
if [ -z "$line" ]; then read line; fi

# apply desired function to the line
deplete_line $line | while read l; do
    echo $l
    sleep 1
done
August 11, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Now that's progress. For a guy who doesn't own one of these "yet" u got it going. Everything you said is right just add "cd to folder containing the bash script". To start the bash script it's got to be in the command. So: bash bash2z | nc localhost 6667 fires it up. nc localhost 6667 will just start nc. So now the code will loop (yeah) for it looks like 5 times, i'll figure that from the code, then finishes, Oh i should mention the static time is displayed when it's not scrolling. That's not part of your script but it is a part of python-listener.py so there's 3 programs at work together here, isn't that touching. So this bash scripting seems to be a good place to start coding.

One thing should be fixed by u though, the second shell will only work once, meaning after scrolling the first text u enter it won't take any new text, i can close it and open it again for new text but that's the long way.

If you need to know anything about the ledarray2 i'm the guy besides the honchos. I was on windows when i started and i wrote about some of it but you definatly need to be with linux for the ledarray2.

August 11, 2009
by Farmerjoecoledge
Farmerjoecoledge's Avatar

Correction: To prolong that data i made a script (1st one good eh!) consists of HELLO WORLD, I'M FINE NOW spaced 5 secs apart and copy her right into the shell, can make it go indefinatly. Dam good stuff. Next step the rss feed, oh yes, it's not far away.

Post a Reply

Please log in to post a reply.

Did you know that you need to think about wires differently when you're transmitting signals more than a few inches? Learn more...