3

I tried to find solution, but still stuck with it. I want to use PyVisa to control function generator. I have a waveform which is a list of values between 0 and 16382 Then I have to prepare it in a way that each waveform point occupies 2 bytes. A value is represented in big-endian, MSB-first format, and is a straight binary. So I do binwaveform = pack('>'+'h'*len(waveform), *waveform) And then when I try to write it to the instrument with AFG.write('trace ememory, '+ header + binwaveform) I get an error:

  File ".\afg3000.py", line 97, in <module>
    AFG.write('trace ememory, '+ header + binwaveform)
TypeError: Can't convert 'bytes' object to str implicitly

I tried to solve it with AFG.write('trace ememory, '+ header + binwaveform.decode()) but it looks that by default it tries to use ASCII characters what is not correct for some values: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 52787: invalid start byte

Could you please help with it?

2
  • The error is arising because you are trying to concatenate a str with a bytes object. I am unfamiliar with the library you are using, but I suspect the function takes bytes. Commented Jul 25, 2017 at 8:53
  • Yes @AlastairMcCormack explained how to convert it. write function takes strings. Commented Jul 25, 2017 at 9:32

1 Answer 1

2

binwaveform is a packed byte array of an integer. E.g:

struct.pack('<h', 4545)
b'\xc1\x11'

You can't print it as it makes no sense to your terminal. In the above example, 0xC1 is invalid ASCII and UTF-8.

When you append a byte string to a regular str (trace ememory, '+ header + binwaveform), Python wants to convert it to readable text but doesn't know how.

Decoding it implies that it's text - it's not.

The best thing to do is print the hex representation of it:

import codecs
binwaveform_hex = codecs.encode(binwaveform, 'hex')
binwaveform_hex_str = str(binwaveform_hex)
AFG.write('trace ememory, '+ header + binwaveform_hex_str)
Sign up to request clarification or add additional context in comments.

1 Comment

binwaveform_hex was still a byte array, not accepted by the write function, so I do `AFG.write('trace ememory, '+ header + str(binwaveform_hex)). No more error in python, but no writing effect on AFG side. But it has to be something else... Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.